這篇文章給大家介紹使用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)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
新聞標題:使用JavaScript怎么實現(xiàn)一個跟隨鼠標移動的盒子-創(chuàng)新互聯(lián)
網(wǎng)頁鏈接:http://www.chinadenli.net/article10/iddgo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、域名注冊、動態(tài)網(wǎng)站、微信小程序、網(wǎng)站內(nèi)鏈、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容