js#原生#拖拽组件的实现

    技术2024-09-29  51

    实现拖拽组件

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> #box { position: relative; width: 200px; height: 20px; background: red; cursor: move; } .parent { border: 1px solid #0000FF; position: absolute; } </style> </head> <body> <div class="parent" id='parent'> <div id="box"></div> <div> hello world </div> <div>welcome to login</div> <form action=""> <input type="text" placeholder="输入用户名字"><br> <input type="password" placeholder="输入用户名字"><br> <button type='button'>login </button><br> </form> </div> </body> <script type="text/javascript"> var box = document.getElementById("box"); var parent = document.getElementById("parent"); </script> <script type="text/javascript"> box.onmousedown = function(event) { var e = event || window.event; var dx = event.clientX - parent.offsetLeft var dy = event.clientY - parent.offsetTop if (typeof box.setCapture !== 'undefined') { box.setCapture(); } // 鼠标按下 定义事件 //鼠标松开 取消事件 document.onmousemove = function(e) { var e = e || window.event var X = e.clientX - dx var Y = e.clientY - dy if (X < 0) { X = 0 } else if (X > window.innerWidth - parent.offsetWidth) { X = window.innerWidth - parent.offsetWidth } if (Y < 0) { Y = 0 } else if (Y > window.innerHeight - parent.offsetHeight) { Y = window.innerHeight - parent.offsetHeight } parent.style.left = X + 'px' parent.style.top = Y + 'px' } document.onmouseup = function() { this.onmousemove = null this.onmouseup = null if (typeof box.releaseCapture != 'undefined') { box.releaseCapture() } } } </script> </html>
    Processed: 0.011, SQL: 9