原生JavaScript实现元素拖拽功能封装与使用指南
作者:微光时间:2026-10-30 17:11:31浏览:546
本文详细介绍了一种基于原生JavaScript封装的通用拖拽方法。通过定义核心函数drag,支持指定拖动目标及可选的拖动触发区域。文章包含完整的代码逻辑解析、坐标计算原理以及具体的调用示例,帮助开发者快速实现网页元素的自由拖动交互功能。
拖拽功能核心代码实现
相关实现代码如下:
function drag(t,p){
var point = p || null,
target = t || null,
resultX = 0,
resultY = 0;
(!point)? point = target : ''; //如果没有拖动点,则拖动点默认为整个别拖动元素
function getPos(t){
var offsetLeft = 0,
offsetTop = 0,
offsetParent = t;
while(offsetParent){
offsetLeft+=offsetParent.offsetLeft;
offsetTop+=offsetParent.offsetTop;
offsetParent = offsetParent.offsetParent;
}
return {'top':offsetTop,'left':offsetLeft};
}
function core(){
var width = document.body.clientWidth || document.documentElement.clientWidth,
height = document.body.clientHeight || document.documentElement.clientHeight;
maxWidth = width - target.offsetWidth,
maxHeight = height - target.offsetHeight;
(resultX >= maxWidth)? target.style.left = maxWidth+'px' : (resultX > 0)?target.style.left = resultX +'px': ''; //重置默认位置。
(resultY >= maxHeight)? target.style.top = maxHeight +'px' : (resultY > 0)?target.style.top = resultY +'px':''; //重置默认位置。
point.onmousedown=function(e){
var e = e || window.event,
coordX = e.clientX,
coordY = e.clientY,
posX = getPos(target).left,
posY = getPos(target).top;
point.setCapture && point.setCapture(); //将Mouse事件锁定到指定元素上。
document.onmousemove=function(e){
var ev = e || window.event,
moveX = ev.clientX,
moveY = ev.clientY;
resultX = moveX - (coordX - posX); //结果值是坐标点减去被拖动元素距离浏览器左侧的边距
resultY = moveY - (coordY - posY);
(resultX > 0 )?((resultX < maxWidth)?target.style.left = resultX+'px' : target.style.left = maxWidth+'px') : target.style.left = '0px';
(resultY > 0 )?((resultY < maxHeight)?target.style.top = resultY+'px' : target.style.top = maxHeight+'px') : target.style.top = '0px';
ev.stopPropagation && ev.stopPropagation();
ev.preventDefault;
ev.returnValue = false;
ev.cancelBubble = true;
};
};
document.onmouseup=function(){ // 解决拖动时,当鼠标指向的DOM对象非拖动点元素时,无法触发拖动点的onmousedown的BUG。
document.onmousemove = null;
point.releaseCapture && point.releaseCapture(); // 将Mouse事件从指定元素上移除。
};
point.onmouseup=function(e){
var e = e || window.event;
document.onmousemove = null;
point.releaseCapture && point.releaseCapture();
};
}
core();
window.onresize = core;
}
函数调用与参数说明
具体调用方法如下:
drag(t,p)
/*
* 说明
* t 表示被拖动的元素
* p 表示拖动点
*/
// 注意:如果省略拖动点,默认可拖动的区域是整个被拖动元素
以上便是关于该原生JS拖拽方法的完整介绍,希望能为您的开发工作提供帮助。
作者最新文章
JavaScript零基础入门:从环境搭建到运行第一段代码
2026-11-05 15:29:58
HTML链接中javascript:void(0)的作用及现代替代方案
2026-11-05 10:07:47
在线调试 JS 时怎么引入 jQuery 或 Vue 等第三方库
2026-11-05 08:53:56
原生JavaScript实现简易颜色选择器原理与代码
2026-11-03 23:22:19
JS原生表单序列化:FormData与URLSearchParams用法详解
2026-11-03 23:13:21
