我正在创建一个页面,我希望该图像在鼠标悬停时能够稍微移动,就像视差效果一样。
所以我已经设法使图像稍微移动了。我所做的就是将图像位置与鼠标坐标关联(我已经注意到了我的错误)。发生的情况是图像几乎离开了视点,因为它到达了我给的实际位置。我试图给图像带来负的空白,但没有成功。
我正在寻找的输出是当用户的鼠标悬停在图像上时,它将仅跟随鼠标方向移动几个像素,并且当用户停止悬停时,图像应返回到其原始位置。
我该如何解决?
$('.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">
答案 0 :(得分: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>