JavaScript 实现可拖拽元素的 Move 对象封装
作者:异步漫步时间:2026-10-23 21:46:14浏览:153
本文介绍了一个用于实现网页元素拖拽功能的 JavaScript Move 对象。该对象封装了页面坐标获取、鼠标按下、移动及释放等核心逻辑,通过监听 onmousedown、onmousemove 和 onmouseup 事件,动态修改元素的 position、left、top 和 zIndex 属性,从而实现流畅的拖拽交互效果。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>JavaScript Data Access Test</title> </script> <style type="text/css"> #div{ background: #ccc; height: 30px; } #div2{ background:#f00; height: 30px; width: 100px; } #d{ background:#ccc; } </style> </head> <body> <div id="div2">move me pls</div> </body> </html> 注意:引入外部 JavaScript 文件后,通常需要刷新页面才能执行相关脚本。
Move 对象核心代码解析
以下是实现该功能的关键代码部分:
具体代码实现如下:
var Move = {
$: function(id){
return (typeof id == "object") ? id : document.getElementById(id);
},
pageX: function(elem){ //获取目标elem的X坐标
return elem.offsetParent ? //如果能继续得到上一个元素,增加当前的偏移量并继续向上递归
elem.offsetLeft + this.pageX(elem.offsetParent) : elem.offsetLeft;
},
pageY: function(elem){ //获取目标elem的Y坐标
return elem.offsetParent ? elem.offsetTop + this.pageX(elem.offsetParent) : elem.offsetTop;
},
make: function(id){
var elem = this.$(id);
var oldXY = null;
var newXY = null;
var x = 0; //记录初始化是目标elem的x坐标
var y = 0; //记录初始化是目标elem的y坐标
var t = this;
elem.onmouseover = function(e){
this.style.cursor = "default";
}
elem.onmousedown = function(e){
e = e || window.event;
this.style.position = "absolute";
this.style.cursor = "move";
x = t.pageX(this);
y = t.pageY(this);
var that = this;
oldXY = {
x: e.clientX,
y: e.clientY
}; //获取鼠标在按下的时候的坐标
document.onmousemove = function(e){
e = e || window.event;
newXY = {
x: e.clientX,
y: e.clientY
}; //获取鼠标在移动过程中的坐标
that.style.left = (newXY.x - oldXY.x + x) + "px";
that.style.top = (newXY.y - oldXY.y + y) + "px";
that.style.zIndex = "100";
}
}
elem.onmouseup = function(e){
this.style.cursor = "default";
this.style.zIndex = "0";
document.onmousemove = function(e){ //在放开鼠标的时候覆盖掉mousemove事件函数
return;
}
}
}
} 作者最新文章
JavaScript怎么遍历对象的Symbol键和不可枚举属性
2026-11-05 13:13:39
封装一个健壮的JS字符串判空工具函数
2026-11-05 12:16:14
JavaScript合并数组的三种常用方法:concat、扩展运算符与push
2026-11-05 11:22:29
JavaScript立即执行函数(IIFE)是什么及基本语法
2026-11-05 10:51:19
JS对象数组转字符串为什么推荐用JSON.stringify()
2026-11-05 09:40:31
