1. 程式人生 > 其它 >拖拽實現

拖拽實現

<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <metahttp-equiv="X-UA-Compatible"content="IE=edge"> <metaname="viewport"content="width=device-width,initial-scale=1.0"> <title>Document</title> <style> html,body{ width:100%; height:400%; /*skyblue;*/ }
.box{ position:fixed; top:100px; left:200px; width:100px; height:100px; background-color:lightblue; cursor:move; } .container-1{ height:1000px; border:1pxsolidred; } .container-2{ height:1000px; border:1pxsolidblue; } </style> </head> <body>
<divclass="container-1">2323</div> <divclass="container-2">2323</div> <divclass="box"></div>
<script>
/** *拖拽的思路 *滑鼠開始位置A *滑鼠當前位置B(滑鼠移動中隨時計算) *盒子開始位置C * *盒子當前位置D=(B-A)+C * *拖拽觸發的條件 *1滑鼠按住盒子才開始拖動,滑鼠只要抬起則結束拖拽 *2拖拽開始後,滑鼠移動盒子才會跟著移動的 * *滑鼠按住盒子mousedown *+記錄C *+記錄A * *滑鼠移動mousemove *+獲取B *+動態計算出D *+修改盒子的樣式,從而讓盒子跟著移動 * *滑鼠抬起mouseup *+取消拖拽 */

/** *解決滑鼠焦點丟失問題 *+(1)IE/火狐:把盒子和滑鼠繫結在一起 *+setCapture *+releaseCapture *+(2)谷歌 *mousemovemouseup繫結給window */ letbox=document.querySelector('.box');
//獲取邊界值 letHTML=document.documentElement, minL=0, minT=0, maxL=HTML.clientWidth-box.offsetWidth, maxT=HTML.clientHeight-box.offsetHeight; constdown=functiondown(ev){ //記錄滑鼠開始位置和盒子的開始位置
let{top,left}=this.getBoundingClientRect(); this.startT=top; this.startL=left;
//記錄滑鼠座標位置 this.startX=ev.clientX; this.startY=ev.clientY;
//滑鼠按下才進行事件繫結(拖拽開始) //this.setCapture();
//保證move/up中的this還需要是盒子, this._move=move.bind(this); this._up=up.bind(this); window.addEventListener('mousemove',this._move); window.addEventListener('mouseup',this._up); }
//滑鼠移動拖拽中 constmove=functionmove(ev){ //獲取盒子當前的位置 letcurL=ev.clientX-this.startX+this.startL, curT=ev.clientY-this.startY+this.startT;
//邊界判斷 curL=curL<minL?minL:(curL>maxL?maxL:curL); curT=curT<minT?minT:(curT>maxT?maxT:curT);
//修改移動位置 this.style.left=`${curL}px`; this.style.top=`${curT}px`; }
//滑鼠抬起拖拽結束 constup=functionup(ev){ //移除事件繫結 //this.releaseCapture(); window.removeEventListener('mousemove',this._move); window.removeEventListener('mouseup',this._up); }
box.addEventListener('mousedown',down);
//獲取當前盒子資訊視口/位置 //console.log(box.getBoundingClientRect()); </script> </body> </html> 我是Eric,手機號是13522679763