原生JavaScript实现拖拽功能
程序员文章站
2022-06-19 17:14:47
实现 (function(window, document){ var x=0,y=0,element; window.startDarg = function(targeId){ element= document.getElementById(targeId).bind(document); element.attachEvent("onmousedown", mousedownFun) } function mousedownFun...
实现
(function(window, document){
var x=0,y=0,element;
window.startDarg = function(targeId){
element= document.getElementById(targeId).bind(document);
element.attachEvent("onmousedown", mousedownFun)
}
function mousedownFun(e){
e=e||window.event;
x=e.clientX - this.offsetLeft;
y=e.clientY - this.offsetTop;
document.addEventListener("onmousemove", mousemoveFun);
document.addEventListener("onmouseup", mouseupFun);
}
function mousemoveFun(e){
e=e||window.event;
setStyle(element, {left: e.clientX - x + "px", top: e.clientY -y + "px"});
}
function mouseupFun(){
document.removeEventListener('onmousemove', mousemoveFun);
document.removeEventListener('onmouseup', mouseupFun);
}
function setStyle(element, css) {
for (var k in css) {
if (css.hasOwnProperty(k)) {
element.style[k] = css[k]
}
}
}
})(window, document)
讲解
- 关注三个事件:mousedown,mousemove,mouseup。当目标元素触发鼠标按下时,启动拖拽方法。因为鼠标存在过快的情况,所以鼠标移动和鼠标释放时作用在document上的。
- 当鼠标移动时,重新更新目标元素的top和left。
- 当鼠标释放时,取消鼠标移动事件的处理方法。
本文地址:https://blog.csdn.net/baidu_38798835/article/details/107525676