<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body{ height:1200px; background-color: azure; } #drag{ background-color: cornflowerblue; border: 1px solid black; position: absolute; width: 200px; height: 100px; } </style> </head> <body> <div id="drag"> </div> <script> //加入文字之后拖拽容易出现选中字后跳动bug var drag = document.getElementById("drag"), text = document.createTextNode("0"), flag , time =0; drag.appendChild(text); drag.addEventListener("mousedown",dragDiv,false); function dragDiv(e){ flag = true; if(flag){ var handler = setInterval(function(){ time+=0.02; drag.innerHTML =time.toFixed(2); if(!flag){ clearInterval(handler); } },20) } var x=e.layerX||e.offsetX; var y=e.layerY||e.offsetY; document.addEventListener("mousemove",docMove,false); document.addEventListener("mouseup",function(){ flag = false; },false); function docMove(e){ if(flag){ e.preventDefault; var l =parseInt(drag.style.left); var t =parseInt(drag.style.top); drag.style.left = -x+e.pageX+"px"; drag.style.top = -y+e.pageY +"px"; } } } </script> </body> </html>
时间: 2024-10-02 03:52:36