原生JS实现弹出窗口的拖拽
上一篇说了一下弹出窗口功能的实现思路,一般情况下紧接着就会需要做到弹窗的移动,当然现在有很插件、库比如hammer可以使用,效率也非常好。但我觉得还是有必要了解一下原生JS的实现思路及方式,如下:
思路:拖动这个操作起始分为三个部分:
- 鼠标左键按下,此时才开始可以拖动;
- 鼠标移动,拖动开始;根据光标的移动给div相对应的纵轴、横轴的偏移;
- 鼠标左键松手,拖动结束,不可以再拖动了。
每一步需要做的事:
1中需要将初始化的拖动标示量置为true(可以拖动了)、记录光标起始坐标和div的起始坐标
2中记录光标移动量,并将光标偏移量实时反映到div的坐标位置中去,div坐标实时同步光标移动,从而达到拖动效果
3拖动标示量置为false(不可以拖动了)
具体实现拖拽的JS代码:
function DivMove(divId, h2Tag) { var oWin = document.getElementById(divId); var oH2 = oWin.getElementsByTagName(h2Tag)[0]; var bDrag = false; var disX = disY = 0; oH2.onmousedown = function (event) { var event = event || window.event; bDrag = true; disX = event.clientX - oWin.offsetLeft; disY = event.clientY - oWin.offsetTop; this.setCapture && this.setCapture(); return false }; document.onmousemove = function (event) { if (!bDrag) return; var event = event || window.event; var iL = event.clientX - disX; var iT = event.clientY - disY; var maxL = document.documentElement.clientWidth - oWin.offsetWidth; var maxT = document.documentElement.clientHeight - oWin.offsetHeight; iL = iL < 0 ? 0 : iL; iL = iL > maxL ? maxL : iL; iT = iT < 0 ? 0 : iT; iT = iT > maxT ? maxT : iT; oWin.style.marginTop = oWin.style.marginLeft = 0; oWin.style.left = iL + "px"; oWin.style.top = iT + "px"; return false }; document.onmouseup = window.onblur = oH2.onlosecapture = function () { bDrag = false; oH2.releaseCapture && oH2.releaseCapture(); }; }
posted on 2017-03-30 18:06 codingHeart 阅读(2971) 评论(1) 编辑 收藏 举报