標籤:turn html charset 處理 clientx color htm cti space
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> #box { width: 300px; height: 300px; background: red; position: absolute; } </style></head><body> <div id="box"> 快來托我吧 </div></body></html><script> //引入 var box = document.getElementById("box");//滑鼠按下 box.onmousedown = function (e) { var e = e || event; var x = e.offsetX; var y = e.offsetY;//在文檔頁面上移動
document.onmousemove = function (e) { var e = e || event; var l = e.clientX - x; var t = e.clientY - y; //邊界處理 var left = document.documentElement.clientWidth - 300; var top = document.documentElement.clientHeight - 300; l = l < 0 ? 0 : (l > left ? left : l); t = t < 0 ? 0 : (t > top ? top : t); box.style.left = l + "px" box.style.top = t + "px"; //阻止預設行 return false; } //滑鼠離開
document.onmouseup = function () { document.onmousemove = null; } }</script>
小盒子拖拽