Home > Article > Web Front-end > js code to implement mouse dragging div instance
This article mainly shares with you the js code to implement mouse dragging div examples, hoping to help everyone.
Directly upload the code, simple and practical.
<!DOCTYPE HTML><html><head><meta charset="utf-8"><title></title> <script type="text/javascript" src='./js/jquery-1.8.3.min.js'></script> <style type="text/css">#ptest{ width: 200px; height: 200px; background: red; position: absolute;/*这很关键*/ left: 40%; top:37%;}#ptest:active{ cursor: move;}</style></head><body><p id="ptest">来,拖拽我啊~</p><script type="text/javascript">var opTest = document.getElementById("ptest"); darg(opTest);function darg(obj){ //鼠标按下 obj.onmousedown = function(ev){ //IE直接用event或者window.event得到事件本身,而在其他浏览器函数要获取到事件本身需要从函数中传入 var oevent = ev || event; var distanceX = oevent.clientX - this.offsetLeft; var distanceY = oevent.clientY - this.offsetTop; //鼠标移动 document.onmousemove = function(ev){ var oevent = ev || event; obj.style.left = oevent.clientX - distanceX + 'px'; obj.style.top = oevent.clientY - distanceY + 'px'; }; //鼠标放开 document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; }; }; }</script></body></html>
Related recommendations:
jQuery uses the drag effect to achieve free dragging div_jquery
The above is the detailed content of js code to implement mouse dragging div instance. For more information, please follow other related articles on the PHP Chinese website!