jQuery鼠标悬停效果错误,鼠标移出事件总是触发几次。

6
我有一个简单的画廊网格,其中包含一个嵌套的 span 显示标题,我想在鼠标悬停时将其向上滑动,并在鼠标移出时隐藏。
一切都很好,除了当鼠标移动到标题所在位置和/或从瓷砖底部悬停出去时,悬停效果会无法控制地重复几次。
起初我以为可能是因为 span 包含在锚点内部,而锚点是悬停触发器,但将其移出也没有用。
有什么想法吗?
演示在这里:http://www.winterealm.com/gallery/ 标记:
<div class="gallery_container">
    <ul>
        <li><a href=""><img src="assets/img/artistisch.jpg" alt="aaa"/><span class="title">Category A</span></a></li>
        <li><a href=""><img src="assets/img/attraktiv.jpg" alt="bbb"/><span class="title">Category B</span></a></li>
        <li><a href=""><img src="assets/img/historisch.jpg" alt="ccc"/><span class="title">Category C</span></a></li>
        <li><a href=""><img src="assets/img/popart.jpg" alt="ddd"/><span class="title">Category D</span></a></li>
        <li><a href=""><img src="assets/img/portrait.jpg" alt="eee"/><span class="title">Category E</span></a></li>
        <li><a href=""><img src="assets/img/sketch.jpg" alt="fff"/><span class="title">Category F</span></a></li>
    </ul>
</div>

这是jQuery

$(document).ready(function(){
    $('.gallery_container a').mouseover(function(){
        $(this).children('.title').animate({
            opacity: 100,
            bottom: 0
        },200);
    });

    $('.gallery_container a').mouseout(function(){
        $(this).children('.title').animate({
            opacity: 0,
            bottom: -30
        },200);
    });
});
3个回答

8

这里的问题在于mouseover事件在鼠标移动到元素或子元素上时会触发。尝试改用mouseenter和mouseleave事件。


是的,最短的解决方案就是最好的!这似乎是做事情的方式!非常感谢! - Winterain

4

试试这个。

$(document).ready(function() {
$('.gallery_container a').hover(function() {
    $(this).children('.title').stop().animate({
        opacity: 100,
        bottom: 0
    }, 200);
}, function() {
    $(this).children('.title').stop().animate({
        opacity: 0,
        bottom: -30
    }, 200);
}); 
});

您可以在这里看到实时演示 - http://jsfiddle.net/8Hd7s/

这也可以,但是有一个小问题,当快速滚动鼠标经过整行时,幻灯片不会自动播放。适用于您不希望每次经过时都进行动画的情况...感谢解决方案! - Winterain
根据您最初的问题,我认为那就是您试图避免的。您可以通过在动画函数之前删除.stop()来轻松更改此设置。 - Austin Brunkhorst
嗨,@AustinBrunkhorst,你能帮忙解决这个问题吗:http://stackoverflow.com/questions/31835128/jquery-onmouseover-selection-attribute/31835344#31835344 - Nuno Sarmento

0

因此,您可能希望实现一个非常简单的锁定机制,例如:

var fCurrentlyMoving = false;       
$('.gallery_container a').mouseover(function(){
    if (!fCurrentlyMoving) {
        fCurrentlyMoving = true;
        $(this).children('.title').animate({
            opacity: 100,
            bottom: 0
        },200, function() {
            fCurrentlyMoving = false;
        });
    }
});

从竞争条件的角度来看,它并不是完全无懈可击的,但也没有必要。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接