自己封装的一个原生JS拖动方法(推荐)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了自己封装的一个原生JS拖动方法(推荐),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2230字,纯文字阅读大概需要4分钟。
内容图文
![自己封装的一个原生JS拖动方法(推荐)](/upload/InfoBanner/zyjiaocheng/305/a8b944a2b36e4f928db2895f05e87c82.jpg)
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拖动方法(推荐)全部内容,希望文章能够帮你解决自己封装的一个原生JS拖动方法(推荐)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。