拖拽在前端开发中是很常见的功能,也是基本功之一,本文是不限制范围的拖拽也就是最简单的拖拽,鼠标按下对象,拖拽,松开停止!
1,onmousedown事件
2,onmousemove事件
3,onmouseup事件
因为在按下时拖动,所以onmousemove事件在down后才注册,up事件是用来解绑事件,消除事件!
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>简单拖拽</title> <style type="text/css"> * { margin: 0; padding: 0; } #div1 { width: 100px; height: 100px; background: orange; position: absolute; } </style> </head> <body style="height: 500000px;"> <div id="div1"></div> <script type="text/javascript"> function getStyle(obj, attr) { if (obj.currentStyle) { return obj.currentStyle[attr]; } else { return getComputedStyle(obj, null)[attr]; } } var oDiv = document.getElementById('div1'); oDiv.onmousedown = function(ev) { var oEvent = ev || event; // var disX = oEvent.clientX - oDiv.offsetLeft; // var disY = oEvent.clientY - oDiv.offsetTop; var disX = oEvent.clientX - parseInt(getStyle(oDiv, 'left')); var disY = oEvent.clientY - parseInt(getStyle(oDiv, 'top')); document.onmousemove = function(ev) { var oEvent = ev || event; oDiv.style.left = oEvent.clientX - disX + 'px'; oDiv.style.top = oEvent.clientY - disY + 'px'; }; document.onmouseup = function() { document.onmousemove = null; document.onmouseup = null; }; return false; }; </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。