如何给出相对于中心的位置坐标?

问题描述 投票:0回答:1

我正在创建一个页面,我希望图像在鼠标悬停时略微移动,就像视差效果一样。

所以我已经设法让图像略微移动。我所做的是将图像位置与鼠标坐标相关联(我已经注意到了我的错误)。会发生的是图像几乎离开了视点,因为它会转到我给出的实际位置。我试图给图像一个负余量,但没有成功。

我正在寻找的输出是当用户的鼠标悬停在图像上时,它将沿着鼠标方向移动几个像素,当用户停止悬停时,图像应该返回到其原始位置。

我该如何解决这个问题?

$('.img-top').mousemove(function(e) {
  var x = -(e.pageX + this.offsetLeft) / 100;
  var y = -(e.pageY + this.offsetTop) / 100;
  $(this).css('left', x + 'px ');
  $(this).css('top', y + 'px ');
});
.img-top {
  height: 75vh;
  width: auto;
  position: relative;
  //    margin-left: -50vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="full-img img-top lrrh" src="https://dummyimage.com/1200x400/000/fff" alt="image alt descrp">
javascript jquery css performance
1个回答
0
投票

在下面的示例中,我为鼠标离开图像时添加了一个额外的事件处理程序。然后它清除由mousemove事件添加的css。我添加了一些额外的CSS来清理示例,并使它们在发生时更加明显。

$('.img-top').mousemove(function(e) {
  var x = ((e.pageX) + (this.offsetLeft)) / 100;
  var y = ((e.pageY) + (this.offsetTop)) / 100;
  $(this).css('left', x + 'px ');
  $(this).css('top', y + 'px ');
  
  update_info($(this), e);
});

$('.img-top').mouseleave(function(e) {
  $(this).css('left', '0px');
  $(this).css('top', '0px');
  
  update_info($(this), e);
});

function update_info(e, m) {
  var i = $('.info'),
      o = e.offset();
      i.empty().append(''
      +'<p>[Image] x: '+Math.round(o.left)+'px - y: '+Math.round(o.top)+'px</p>'
      +'<p>[Mouse] x: '+Math.round(m.pageX)+'px - y: '+Math.round(m.pageY)+'px</p>');
}
.fill {
  background-color:rgb(255,255,255);
  display:block;
  height:100%;
  width:100%;
}

.image-viewpane {
  display:inline-block;
  height:200px;
  width:600px;
  padding:10px;
  text-align:center;
  border:4px solid red;
}

.img-top {
  position:relative; 
  display:inline-block;
  height: 100%;
  width:auto;
  box-shadow:0px 0px 4px rgb(255,0,0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fill">
  <div class="image-viewpane">
    <img class="img-top" src="https://dummyimage.com/1200x400/000/fff" alt="image alt descrp"/>
  </div> 
  <div class="info"><p>Waiting for mouse movement ...</p></div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.