自己封装的一个原生JS拖动方法(推荐)
网络编程 2021-07-04 19:19www.168986.cn编程入门
狼蚁网站SEO优化长沙网络推广就为大家带来一篇自己封装的一个原生JS拖动方法(推荐)。长沙网络推广觉得挺不错的,希望对大家有所帮助。一起跟随长沙网络推广过来看看吧,祝大家游戏愉快哦
代码
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 {'':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. = maxHeight +'px' : (resultY > 0)?target.style. = resultY +'px':''; //重置默认位置。 point.onmousedown=function(e){ var e = e || window.event, coordX = e.clientX, coordY = e.clientY, posX = getPos(target).left, posY = getPos(target).; 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. = resultY+'px' : target.style. = maxHeight+'px') : target.style. = '0px'; ev.sPropagation && ev.sPropagation(); 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拖动方法(推荐)全部内容了,希望大家多多支持狼蚁SEO~
上一篇:原生JS查找元素的方法(推荐)
下一篇:SelecT下拉框选中和取值的解决方法
编程语言
- 宿迁百度关键词排名指南:实现精准营销的关键
- 四川SEO优化怎么做网络推广
- 立昂技术备案老域名收购:如何为您的业务赋能
- 安徽百度关键词seo贵不贵,一般需要多少钱
- 吉林百度快照排名怎么做电话营销
- 多伦新手做SEO怎么做
- 甘肃优化关键词排名推广怎么做论坛营销
- 沙雅SEO网站推广:提升您的在线可见性
- 四川SEO优化如何提升销售额和销售量
- 聂荣网站排名优化:提升网站可见性的全方位指
- 涞水SEO:提升地方企业在线可见性的策略
- 辽宁百度seo排名怎样做网站排名
- 临湘哪有关键词排名优化:提升网站可见度的关
- 黑龙江百度网站优化有没有优惠
- 凉城优化关键词排名推广:提升您的网络可见性
- 萝北整站优化:提升您网站流量和排名的全面指