jQuery在父项悬停时触发子元素

时间:2013-04-23 05:11:49

标签: jquery

我有一个嵌套div的列表,它们两个图像完全堆叠在一起。我已经建立了一个悬停效果,可以创建平滑的过渡效果。但是,效果仅在鼠标位于图像上时触发,而在鼠标位于链接上方时不会触发。这是我的简要想法代码:

<ul id="shortcuts" class="sitewidth">
    <li>
        <a href="#">
            <div class="shortcuticon box">
                <img src="images/icon-learn.png" alt="" class="a">
                <img src="images/icon-learn-hover.png" alt="" class="b">
            </div>
        </a>
    </li>
    <li>
        <a href="#">
            <div class="shortcuticon box">
                <img src="images/icon-learn.png" alt="" class="a">
                <img src="images/icon-learn-hover.png" alt="" class="b">
            </div>
        </a>
    </li>
    <li>
        <a href="#">
            <div class="shortcuticon box">
                <img src="images/icon-learn.png" alt="" class="a">
                <img src="images/icon-learn-hover.png" alt="" class="b">
            </div>
            <h2>Hello World!</h2>
        </a>
    </li>

    <script type='text/javascript'>
        $(document).ready(function(){
            $("img.a").hover(function() {
                $(this).stop().animate({"opacity": "0"}, "slow");
            }, function() {
                $(this).stop().animate({"opacity": "1"}, "slow");
            });
        });
    </script>
</ul>

我确实认识到hove函数应该在#shortcuts li a而不是图像本身上完成。但是这段代码很有用,可以让你大致了解我在寻找什么。非常感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

试试这个: - 不确定你想要出现的确切程度,但这是我的尝试。

只有一张图片*

http://jsfiddle.net/tQwDk/

两张图片

http://jsfiddle.net/GcJG5/

 $("#shortcuts li").hover(

function () {
    $('img.a', this).stop().animate({
        "opacity": "0"
    }, "slow");
},

function () {
    $('img.a', this).stop().animate({
        "opacity": "1"
    }, "slow");
});

答案 1 :(得分:0)

尝试

$(document).ready(function() {
    $("a").has('img.a').hover(function() {
            $('img.a', this).stop().animate({
                        "opacity" : "0"
                    }, "slow");
        }, function() {
            $('img.a', this).stop().animate({
                        "opacity" : "1"
                    }, "slow");
        });
});

答案 2 :(得分:0)

我的第一个想法是向Hello World h2添加悬停事件,并在图片trigger事件上致电hover

$("#shortcuts li a h2").hover(function(){
  $(this).parent.find('img.a').trigger('hover');
});

不幸的是trigger hover这样的伪选择器是不可能的。

幸运的是,我相信以下内容将为您提供所需的结果。您可以在父链接上使用mouseentermouseleave,然后查找子图像并为其设置动画。

$(document).ready(function(){
    $("#shortcuts li a").mouseenter(
        function() {
            $(this).find('img.a').stop().animate({"opacity": "0"}, "slow");
     }).mouseleave(
        function() {
            $(this).find('img.a').stop().animate({"opacity": "1"}, "slow");
    });

});
相关问题