您好,登錄后才能下訂單哦!
這篇文章給大家介紹使用JavaScript怎么實現(xiàn)一個跟隨鼠標移動的盒子,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
代碼:
<!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; // 鼠標按下 獲取鼠標距離頁面左側(cè)距離 var x = e.clientX; // 獲取鼠標距離頁面上側(cè)距離 var y = e.clientY; // 元素距離頁面左側(cè)距離 var elex = div.offsetLeft; // 元素距離頁面上側(cè)距離 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.左側(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; } // 鼠標移動過程中 獲取鼠標距離頁面距離 - 鼠標距離元素的距離 =元素的left top值 div.style.left = leftx + 'px'; div.style.top = lefty + 'px'; } // 抬起清除移動事件 document.onmouseup = function() { document.onmousemove = null; } // 阻止默認事件 return false; } </script> </body> </html>
關(guān)于使用JavaScript怎么實現(xiàn)一個跟隨鼠標移動的盒子就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。