gpt4 book ai didi

javascript - 我怎样才能给出相对于中心的位置坐标?

转载 作者:行者123 更新时间:2023-11-28 00:02:44 25 4
gpt4 key购买 nike

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

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

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

我该如何解决?

$('.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">

最佳答案

在下面的示例中,我为鼠标离开图像添加了一个额外的事件处理程序。然后它清除由 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>

关于javascript - 我怎样才能给出相对于中心的位置坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55909670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com