0

我发现这个 codepen https://codepen.io/plankton/pen/aGejYq工作正常。

我有一个跟随光标的元素。但我不知道如何将它限制在一个 div 中,当光标进入这个 div 时,这个元素会顺利到达光标。如果我从 div 中离开,则只有元素返回到他的位置。就像在这个网站上的视频一样https://obys.agency/

如果它可以单独使用 JavaScript 完成,那对我来说没问题。

jQuery(document).ready(function() {

  var mouseX = 0,
    mouseY = 0;
  var xp = 0,
    yp = 0;

  $(document).mousemove(function(e) {
    mouseX = e.pageX - 30;
    mouseY = e.pageY - 30;
  });

  setInterval(function() {
    xp += ((mouseX - xp) / 6);
    yp += ((mouseY - yp) / 6);
    $("#circle").css({
      left: xp + 'px',
      top: yp + 'px'
    });
  }, 20);

});
body,
html {
  position: relative;
  height: 100%;
  width: 100%;
  margin: 0;
  background-color: #000000;
}

.circle {
  position: absolute;
  border: solid 1px #ccc;
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="circle" class="circle"></span>

4

1 回答 1

0

这就是我想出的。

jQuery(document).ready(function() {
  
  const constraint = document.getElementById('constraint');
  const circle = document.getElementById('circle');

  var mouseX = 0, mouseY = 0;
  var xp = 0, yp = 0;
   
  $(document).mousemove(function(e){
     if (e.target === constraint || (e.target === circle && e.pageX >= 0 && e.pageX <= 300 && e.pageY >= 0 && e.pageY <= 300)) {
        mouseX = e.pageX - 30;
        mouseY = e.pageY - 30;
     } else {
        mouseX = 0;
        mouseY = 0;
     }
  });

  setInterval(function(){
     xp += ((mouseX - xp)/6);
     yp += ((mouseY - yp)/6);
     $("#circle").css({left: xp +'px', top: yp +'px'});
  }, 20);

});
@import url(https://fonts.googleapis.com/css?family=Roboto:400,900);
body, html {
    position: relative;
    height: 100%; 
    width : 100%;  
    margin: 0;
    background-color: #000000;
}

.circle {
    position: absolute;
    border: solid 1px #ccc;
    width: 60px; 
    height: 60px; 
    border-radius: 50%;  
}

.constraint {
    position: absolute;
    width: 300px;
    height: 300px;
    background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="constraint" class="constraint">
  <span id="circle" class="circle"></span>
</div>

于 2020-11-10T16:26:59.857 回答