案例:简易的Div拖拽
Posted f6056
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了案例:简易的Div拖拽相关的知识,希望对你有一定的参考价值。
案例:简易的Div拖拽
鼠标移入Div区域后,按下鼠标左键,可以拖动Div移动;松开鼠标左键,Div拖动停止。同时要求Div不能拖出屏幕显示区域外。
拖拽原理:距离不变、三个事件(onmousedown、onmousemove、onmouseup)
解决问题:
1、拖拽过程中,鼠标容易滑出Div区块;
2、防止Div拖出页面:修正位置;
3、解除绑定事件:鼠标左键抬起后,Div不再随着鼠标移动而发生位置变化;
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>习题-拖拽Div滑块</title> <style> * margin: 0;padding: 0; div width: 100px; height: 100px; margin-bottom: 0px; background-color: purple; position: absolute; </style> <script> window.onload = function () //此处写代码 </script> </head> <body> <div id=‘div1‘></div> </body> </html>
参考代码:
function getPos(ev) var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; return x: ev.clientX + scrollTop, y: ev.clientY + scrollLeft ; var oDiv = document.getElementById(‘div1‘); var disX = 0; var disY = 0; oDiv.onmousedown = function (ev) var oEvent = ev || event; disX = getPos(oEvent).x - oDiv.offsetLeft; disY = getPos(oEvent).y - oDiv.offsetTop; document.onmousemove = function (ev) var oEvent = ev || event; var l = oEvent.clientX - disX; var t = oEvent.clientY - disY; if (l < 0) l = 0; else if (l > document.documentElement.clientWidth - oDiv.offsetWidth) l = document.documentElement.clientWidth - oDiv.offsetWidth; if (t < 0) t = 0; else if (t > document.documentElement.clientHeight - oDiv.offsetHeight) t = document.documentElement.clientHeight - oDiv.offsetHeight; oDiv.style.left = l + ‘px‘; oDiv.style.top = t + ‘px‘; document.onmouseup = function () document.onmousemove = null; document.onmouseup = null; return false;
以上是关于案例:简易的Div拖拽的主要内容,如果未能解决你的问题,请参考以下文章