分享一个原生的JavaScript拖动方法
更新时间:2016年09月25日 10:18:18 作者:卷柏的花期
本文给大家分享的是基于JavaScript的setCapture方法实现的拖动效果,非常的简单实用,有需要的小伙伴可以参考下
代码:
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 表示拖动点 */ // 注意:如果省略拖动点,默认可拖动的区域是整个被拖动元素
相关文章
解决IE下select标签innerHTML插入option的BUG(兼容IE,FF,Opera,Chrome,Safa
在ie下面使用innerHTML来插入option选项的话,ie会去掉前面的<option>,并拆分成多个节点,这样会造成select的出错2010-05-05
js禁止查看源文件屏蔽Ctrl+u/s、F12、右键等兼容IE火狐chrome
最近想给JS特效与模板预览页面加上屏蔽查看源文件,防治整理不易的源码被轻易拿走,发现IE、火狐、chrome等各类浏览器支持不一样。下面是脚本之家整理的一些屏蔽总结2020-10-10
利用js判断浏览器类型(是否为IE,Firefox,Opera浏览器)
我们开发的人来说经常要加个判断,要不可能某些功能没法正常使用。要是没加个判断就会给大家带来些麻烦2013-11-11


最新评论