2 回答
TA贡献1827条经验 获得超7个赞
使用 mouseenter 添加 mousemove 侦听器并在 mouseleave 中将其删除可以解决大部分问题。另一部分是,如果图像离开容器时鼠标正下方,则鼠标仍在 child 上方。
相对于鼠标向图像位置添加一些额外的偏移量有助于消除其余的错误
$('div').on('mouseenter', function() {
var img = $(this).find("figure");
var offset = img.offset();
var originLeft = offset.left;
var originTop = offset.top;
// only listen to move on this instance
$(this).mousemove(function(e) {
img.addClass('active').css({
transform: 'translateX(' + (e.pageX - originLeft / 2) + 'px) translateY(' + (e.pageY+10 - originTop) + 'px)'
});
})
}).on('mouseleave', function() {
// remove the mousemove listener
$(this).off('mousemove').find("figure").removeClass('active').css({
transform: 'translateX(0) translateY(0)'
});
});
div {
height: 150px;
width: 150px;
background: #eee;
margin-bottom: 30px
}
div:nth-child(2) {
background: #ccc;
}
figure {
display: block;
height: 50px;
width: 50px;
background: blue;
margin: 0;
transition: transform 500ms ease;
}
.active {
transition: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<figure></figure>
</div>
<div>
<figure></figure>
</div>
TA贡献1808条经验 获得超4个赞
您的问题在这一行:
$('div').mousemove(function(e) {
将其更改为:
$(this).on('mousemove', function(e) {
那是因为您需要解决每个循环中您所在的当前 div 元素:
$('div').each(function() {
片段:
$('div').each(function() {
var img = $(this).find( "figure" );
var offset = img.offset();
var originLeft = offset.left;
var originTop = offset.top;
$(this).on('mousemove', function(e) {
img.addClass('active');
img.css({
transform: 'translateX(' + (e.pageX - originLeft/2 ) + 'px) translateY(' + (e.pageY - originTop) + 'px)'
});
}).on('mouseout', function(e) {
img.removeClass('active');
img.css({
transform: 'translateX(0) translateY(0)'
});
});
});
div {
height: 250px;
width: 250px;
background: #eee;
}
div:nth-child(2) {
background: #ccc;
}
figure {
display: block;
height: 50px;
width: 50px;
background: blue;
margin: 0;
transition: transform 500ms ease;
}
.active {
transition: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<figure></figure>
</div>
<div>
<figure></figure>
</div>
添加回答
举报