跟随鼠标移动的盒子
?跟隨鼠標(biāo)移動的盒子(包括檢測邊界值)
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head> <style>div {position: absolute;top: 0px;left: 0px;width: 100px;height: 100px;background-color: red;} </style><body><div>111111111</div><script>var div = document.getElementsByTagName('div')[0];div.onmousedown = function(e) {e = window.event || e;// 鼠標(biāo)按下 獲取鼠標(biāo)距離頁面左側(cè)距離var x = e.clientX;// 獲取鼠標(biāo)距離頁面上側(cè)距離var y = e.clientY;// 元素距離頁面左側(cè)距離var elex = div.offsetLeft;// 元素距離頁面上側(cè)距離var eley = div.offsetTop;// 相減得到鼠標(biāo)距離元素的距離var X = x - elex;var Y = y - eley;console.log(X, Y);document.onmousemove = function(e) {e = window.event || e;// 鼠標(biāo)移動過程中 獲取鼠標(biāo)距離頁面距離var movex = e.clientX;var movey = e.clientY;// 1.左側(cè)邊界值// 元素移動過程中距離頁面左側(cè)距離var leftx = movex - X;var lefty = movey - Y;// 1.左側(cè)邊界值if (leftx <= 0) {leftx = 0;}// 2.上側(cè)邊界值if (lefty <= 0) {lefty = 0}// 3.右側(cè)邊界值// 頁面可視區(qū)寬 -元素寬var rightx = document.documentElement.clientWidth - div.offsetWidth;if (leftx >= rightx) {leftx = rightx}// 4.下側(cè)邊界值// 頁面可視區(qū)高 -元素高var righty = document.documentElement.clientHeight - div.offsetHeight;if (lefty >= righty) {lefty = righty;}// 鼠標(biāo)移動過程中 獲取鼠標(biāo)距離頁面距離 - 鼠標(biāo)距離元素的距離 =元素的left top值div.style.left = leftx + 'px';div.style.top = lefty + 'px';}// 抬起清除移動事件document.onmouseup = function() {document.onmousemove = null;}// 阻止默認(rèn)事件return false;}</script> </body></html>?
總結(jié)
- 上一篇: 机载雷达导论(第29~36章)
- 下一篇: html常用font-family设置字