拖拽模版
程序员文章站
2022-05-08 08:01:19
对ctrl+a后拖动的问题做了处理 ......
对ctrl+a后拖动的问题做了处理
<!doctype html> <html> <head> <meta charset="utf-8"> <title>title</title> <link rel="stylesheet" href="../reset.css"> <style> .box{ width: 100px; height: 100px; background-color: red; position: absolute; left: 0; top: 0; } </style> </head> <body> <div class="box">111</div> <script> window.onload = function () { var box = document.queryselector(".box"); var boxstart = { left: 0, top: 0 }; var mousestart = { left: 0, top: 0 }; box.onmousedown = function (ev) { // 绑定全局捕获 box.setcapture && box.setcapture(); ev = ev || window.event; // 阻止默认事件兼容性写法 ev.preventdefault?ev.preventdefault():ev.returnvalue=false; // 阻止传播兼容性写法 // ev.stoppropagation?ev.stoppropagation():ev.cancelbubble=true; // 鼠标开始的位置 mousestart.left = ev.clientx; mousestart.top = ev.clienty; // 盒子开始的位置 boxstart.left = box.offsetleft; boxstart.top = box.offsettop; document.onmousemove = function (ev) { ev = ev || window.event; // 鼠标结束的位置 var mouseend = {}; mouseend.left = ev.clientx; mouseend.top = ev.clienty; // 移动的差值 var mouselenx = mouseend.left - mousestart.left; var mouseleny = mouseend.top - mousestart.top; // 移动后的位置 var l = boxstart.left + mouselenx; var t = boxstart.top + mouseleny; // 视口尺寸 var winw = document.documentelement.clientwidth; var winh = document.documentelement.clientheight; // 盒子尺寸 var boxw = box.offsetwidth; var boxh = box.offsetheight; l = l<0?0:l; l = l>=winw-boxw?winw-boxw:l; t = t<0?0:t; t = t>=winh-boxh?winh-boxh:t; box.style.left = l + "px"; box.style.top = t + "px"; }; document.onmouseup = function () { // 释放全局捕获 document.releasecapture && document.releasecapture(); document.onmousemove = document.onmouseup = null; } } } </script> </body> </html>
上一篇: 如何利用GitHub设计一个炫酷的个人网站(含代码)
下一篇: VUE 生命周期 详解