日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

跟随鼠标移动的盒子

發(fā)布時間:2023/12/31 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 跟随鼠标移动的盒子 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

?跟隨鼠標(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é)

以上是生活随笔為你收集整理的跟随鼠标移动的盒子的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。