当将鼠标悬停在div上时,如何遍历行并使用jQuery显示另一个div?

时间:2017-03-09 17:04:25

标签: jquery html hover

我正在尝试显示一个div,当另一个人徘徊时,但我正在努力将其与循环结合起来。

我的HTML是:

    <div class="row">
        <div class="half">
            <img class="restaurant-logo" src=""/>
            <p>Lorem ipsum dolor sit amet. </p>
            <strong><a href="">Continue Reading</a></strong>
            <a class="button order" href="#">Order now</a>
        </div>

        <div class="half image" style="background-image: url();">
            <div class="quote">
                <div class="quote-text"><p>Highlighted text </p></div>
            </div>
        </div>
    </div>
        <div class="row">
        <div class="half">
            <img class="restaurant-logo" src=""/>
            <p>Lorem ipsum dolor sit amet. </p>
            <strong><a href="">Continue Reading</a></strong>
            <a class="button order" href="#">Order now</a>
        </div>

        <div class="half image" style="background-image: url();">
            <div class="quote">
                <div class="quote-text"><p>Highlighted text</p></div>
            </div>
        </div>
    </div>

这个想法是这样的:

当您将鼠标悬停在“立即订购”按钮上时,同一行中的.quote-text会从不透明度0变为不透明度1。

我试图实现每个语句,并且还试图转到父元素并返回到另一个孩子,但由于某种原因,每次我悬停时,所有.quote文本都在变化。

我的jQuery在下面。

$('.order').each( function() {
    $(this).hover(
        function() {
            $('.order').closest('.row').find('.quote').css('opacity', '1');
        },
        function() {
            $('.order').closest('.row').find('.quote').css('opacity', '0');
        }
    );
});

任何帮助都会非常感激,我觉得我很接近,但我的jQuery技能有限,互联网搜索和反复试验对我没有帮助!

1 个答案:

答案 0 :(得分:1)

您遇到的问题是您在悬停时选择了所有.order元素。相反,您可以使用this关键字仅引用引发事件的关键字。试试这个:

$('.order').each( function() {
    $(this).hover(function() {
        $(this).closest('.row').find('.quote').css('opacity', '1');
    }, function() {
        $(this).closest('.row').find('.quote').css('opacity', '0');
    });
});

从那里你可以通过删除多余的each()循环,并在hover()和{{1下同时触发mouseenter的单个函数来使逻辑更简洁。只在适当的mouseleave上调用toggle()的事件:

.quote