We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
关键是3个mouse事件
Codepen.io效果地址
有小细节需要特别注意
addEventListener
document
moveEle.addEventListener
getBoundingClientRect()
e.clientX
moveEle.style.left = moveX + 'px'
<div class="move-container"> <div class="move" style="position:absolute; width:100px; height:100px; background:gold"> </div> </div>
let moveEle = document.querySelector("#move"); let dragging = false; let relaDistanceX = 0; let relaDistanceY = 0; // 1. MouseDown moveEle.addEventListener("mousedown", e => { if (e.target == moveEle) { //active dragging dragging = true; var moveEleDis = moveEle.getBoundingClientRect(); relaDistanceX = e.clientX - moveEleDis.left; relaDistanceY = e.clientY - moveEleDis.top; } }); // 2. MouseUp moveEle.addEventListener("mouseup", e => { dragging = false; }); // 3. MouseMove moveEle.addEventListener("mousemove", e => { if (dragging) { //deploy the distance moveEle.style.left = e.clientX - relaDistanceX + 'px'; moveEle.style.top = e.clientY - relaDistanceY + 'px'; } });
The text was updated successfully, but these errors were encountered:
2020.02.25更新
可以使用
tLeft = e.offsetX tTop = e.offsetY
其中 event.offsetX 指:
event.offsetX
offsetX/Y获取到是触发点相对被触发dom的左上角距离,不过左上角基准点在不同浏览器中有区别,其中在IE中以内容区左上角为基准点不包括边框,如果触发点在边框上会返回负值,而chrome中以边框左上角为基准点。
最后发现一张好图,来自https://segmentfault.com/a/1190000002405897 [JS基础篇--了解JS的clientX、pageX、screenX等方法来获取鼠标坐标详解]
Sorry, something went wrong.
No branches or pull requests
如何使用div完成拖拽效果
关键是3个mouse事件
Codepen.io效果地址
注意
有小细节需要特别注意
addEventListener
最好加载document
上面,不然鼠标移动太快会掉帧,即无法捕捉moveEle这个事件,但是用document
的话,mousedown这个事件一直存在moveEle.addEventListener
,codepen上面用的documnetgetBoundingClientRect()
e.clientX
moveEle.style.left = moveX + 'px'
代码
HTML
JS
The text was updated successfully, but these errors were encountered: