JavaScript實現(xiàn)跟隨鼠標移動的盒子
更新時間:2021年01月28日 08:41:57 作者:搬磚大法
這篇文章主要為大家詳細介紹了JavaScript實現(xiàn)跟隨鼠標移動的盒子,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了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>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
js判斷手機是否安裝并打開app,未安裝則安裝app【兼容Android、ios,親測可用】
這篇文章主要介紹了js判斷手機是否安裝并打開app,未安裝則安裝app,通過調(diào)用瀏覽器判斷app,兼容Android、ios等系統(tǒng),,需要的朋友可以參考下2023-05-05JS實現(xiàn)網(wǎng)頁游戲中滑塊響應(yīng)鼠標點擊移動效果
這篇文章主要介紹了JS實現(xiàn)網(wǎng)頁游戲中滑塊響應(yīng)鼠標點擊移動效果,涉及JavaScript針對頁面鼠標事件、滾動事件及元素屬性等相關(guān)操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10SpringMVC返回json數(shù)據(jù)的三種方式
這篇文章主要介紹了SpringMVC返回json數(shù)據(jù)的三種方式的相關(guān)資料,需要的朋友可以參考下2015-12-12學習javascript面向?qū)ο?掌握創(chuàng)建對象的9種方式
這篇文章主要為大家介紹了創(chuàng)建對象的9種方式,幫助大家更好地學習javascript面向?qū)ο?,感興趣的小伙伴們可以參考一下2016-01-01