欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實(shí)現(xiàn)跟隨鼠標(biāo)移動(dòng)的盒子

 更新時(shí)間:2021年01月28日 08:41:57   作者:搬磚大法  
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)跟隨鼠標(biāo)移動(dòng)的盒子,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了JavaScript實(shí)現(xiàn)跟隨鼠標(biāo)移動(dòng)的具體代碼,供大家參考,具體內(nèi)容如下

跟隨鼠標(biāo)移動(dòng)的盒子(包括檢測邊界值)

效果圖:

代碼:

<!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)移動(dòng)過程中 獲取鼠標(biāo)距離頁面距離
          var movex = e.clientX;
          var movey = e.clientY;
          // 1.左側(cè)邊界值
          // 元素移動(dòng)過程中距離頁面左側(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)移動(dòng)過程中 獲取鼠標(biāo)距離頁面距離 - 鼠標(biāo)距離元素的距離 =元素的left top值
          div.style.left = leftx + 'px';
          div.style.top = lefty + 'px';
 
 
 
        }
        // 抬起清除移動(dòng)事件
      document.onmouseup = function() {
          document.onmousemove = null;
        }
        // 阻止默認(rèn)事件
      return false;
 
    }
  </script>
</body>
 
</html>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論