标签:type move info otto mic 移动 meta 技术 要求
案例:简易的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; }
标签:type move info otto mic 移动 meta 技术 要求
原文地址:https://www.cnblogs.com/f6056/p/11150549.html