如何跟随鼠标反向移动

How to follow mouse movement the opposite direction?

本文关键字:鼠标 移动 跟随 何跟随      更新时间:2023-09-26

我希望有一个div,它沿着鼠标坐标的相反方向,位于div .box内。当你移动鼠标时,红色框应该稍微向相反的方向移动,所以看起来像是一种视差效果。现在它会以你的鼠标速度移动,这不是我想要的。我希望盒子稍微移动一下,这样你就会看到盒子向相反的方向移动一点。我想把方框对准鼠标的中心。

我已经编写了一个脚本,让红框跟随你的鼠标移动,但不知道如何完成以上工作。

$(document).ready(function(){
  $('div.container').on('mousemove',function(e){
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        $('div.box').css({'left': x, 'top': y});
  });
});

http://codepen.io/anon/pen/zBrkGa

尝试将top更改为bottom,将left更改为right可以解决您的问题,例如,

$('div.box').css({'right': x, 'bottom': y});

$(document).ready(function() {
  $('div.container').on('mousemove', function(e) {
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    $('div.box').css({
      'right': x,
      'bottom': y
    });
  });
});
.container {
  margin: 0 auto;
  width: 300px;
  height: 300px;
  border: 1px #000 solid;
  position: relative;
}
.box {
  width: 50px;
  height: 50px;
  border: 1px #000 solid;
  position: absolute;
  right: 200px;
  background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
  <div class="box"></div>
</div>

更新,用于固定100px范围内的盒子,并带有一些延迟

$(document).ready(function() {
  $('div.container').on('mousemove', function(e) {
    var x = (e.pageX - this.offsetLeft);
    var y = (e.pageY - this.offsetTop);
    if(x<100||x>200||y>200||y<100) return false;
    setTimeout(function() {
      $('div.box').css({
        'right': x,
        'bottom': y
      }).text(x+','+y);
    }, 500);
  });
});
.container {
  margin: 0 auto;
  width: 300px;
  height: 300px;
  border: 1px #000 solid;
  position: relative;
}
.box {
  width: 50px;
  height: 50px;
  border: 1px #000 solid;
  position: absolute;
  right: 200px;
  background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
  <div class="box"></div>
</div>

$(document).ready(function(){
 $('div.container').mousemove(function(e){
  let mouseX = e.pageX;
  let mouseY = e.pageY;
   $(this).children('.box').css({
    'transform': 'translate(' + mouseX / -80 + 'px ,' + mouseY / -80 + 'px)
   })
  });
});

负数将以与鼠标移动相反的方式移动对象或div(.box(