有两点值得优化:
一个是position:absolute
如果页面不滚动的情况下,不会出现问题,但如果页面是可滚动的,那悬浮按钮就会出现无法拉出当前窗口范围的问题
改为:postion:fixed,针对窗口固定位置,是个不错的选择!
第二个是拖动没有设置范围限制,即可以拖到窗口之外的地方而无法拖回来,
优化的代码如下:
1 2 3 4 | if(this.x<=0){this.x=0;} if(this.x>=document.body.offsetWidth-70){this.x=document.body.offsetWidth-70;} if(this.y<=0){this.y=0;} if(this.y>=document.body.offsetHeight-70){this.y=document.body.offsetHeight-70;} |
demo请点击:http://csp.sowl.cn/#!/cspShow
参考代码:
css代码如下:
1 2 3 4 5 6 7 8 9 10 11 | #showHomeButton{ position: fixed; top:0; left:0; width: 70px; height: 70px; background: url('../../img/homeBtn.png') no-repeat; background-size:100% 100%; border-radius: 50%; z-index:1000; } |
js代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | export class showHomeButton extends Vue { el:'#wxContent' flag:boolean=false; cur = { x:0, y:0 } nx=null; ny=null; dx=null; dy=null; x=null; y=null; showHomeButton:any; ready(){ this.showHomeButton = document.getElementById("showHomeButton"); this.x=document.body.offsetWidth-100; this.y=document.body.offsetHeight-100; this.showHomeButton.style.left = this.x+"px"; this.showHomeButton.style.top = this.y +"px"; this.showHomeButton.addEventListener("mousedown",()=>{ this.down(); },false); this.showHomeButton.addEventListener("touchstart",()=>{ this.down(); },false) this.showHomeButton.addEventListener("mousemove",()=>{ this.move(); },false); this.showHomeButton.addEventListener("touchmove",()=>{ event.preventDefault(); this.move(); },false) document.body.addEventListener("mouseup",()=>{ this.end(); },false); this.showHomeButton.addEventListener("touchend",()=>{ this.end(); },false); } down(){ this.flag = true; var touch ; if(event.touches){ touch = event.touches[0]; }else { touch = event; } this.cur.x = touch.clientX; this.cur.y = touch.clientY; this.dx = this.showHomeButton.offsetLeft; this.dy = this.showHomeButton.offsetTop; } move(){ if(this.flag){ var touch ; if(event.touches){ touch = event.touches[0]; }else { touch = event; } this.nx = touch.clientX - this.cur.x; this.ny = touch.clientY - this.cur.y; this.x = this.dx+this.nx; this.y = this.dy+this.ny; if(this.x<=0){this.x=0;} if(this.x>=document.body.offsetWidth-70){this.x=document.body.offsetWidth-70;} if(this.y<=0){this.y=0;} if(this.y>=document.body.offsetHeight-70){this.y=document.body.offsetHeight-70;} this.showHomeButton.style.left = this.x+"px"; this.showHomeButton.style.top = this.y +"px"; } } end(){ this.flag = false; } // stopdefault(event) { // var w = x<0?x*-1:x; //x轴的滑动值 // var h = y<0?y*-1:y; //y轴的滑动值 // if(w>h){ //如果是在x轴中滑动 // event.preventDefault(); // } // event.preventDefault(); // } showHome(){ router.go('./cspShow') } } |