這篇文章給大家介紹使用JavaScript怎么實現一個跟隨鼠標移動的盒子,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
代碼:
<!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; // 鼠標按下 獲取鼠標距離頁面左側距離 var x = e.clientX; // 獲取鼠標距離頁面上側距離 var y = e.clientY; // 元素距離頁面左側距離 var elex = div.offsetLeft; // 元素距離頁面上側距離 var eley = div.offsetTop; // 相減得到鼠標距離元素的距離 var X = x - elex; var Y = y - eley; console.log(X, Y); document.onmousemove = function(e) { e = window.event || e; // 鼠標移動過程中 獲取鼠標距離頁面距離 var movex = e.clientX; var movey = e.clientY; // 1.左側邊界值 // 元素移動過程中距離頁面左側距離 var leftx = movex - X; var lefty = movey - Y; // 1.左側邊界值 if (leftx <= 0) { leftx = 0; } // 2.上側邊界值 if (lefty <= 0) { lefty = 0 } // 3.右側邊界值 // 頁面可視區寬 -元素寬 var rightx = document.documentElement.clientWidth - div.offsetWidth; if (leftx >= rightx) { leftx = rightx } // 4.下側邊界值 // 頁面可視區高 -元素高 var righty = document.documentElement.clientHeight - div.offsetHeight; if (lefty >= righty) { lefty = righty; } // 鼠標移動過程中 獲取鼠標距離頁面距離 - 鼠標距離元素的距離 =元素的left top值 div.style.left = leftx + 'px'; div.style.top = lefty + 'px'; } // 抬起清除移動事件 document.onmouseup = function() { document.onmousemove = null; } // 阻止默認事件 return false; } </script> </body> </html>
關于使用JavaScript怎么實現一個跟隨鼠標移動的盒子就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。