更改元素背景图像而不是兄弟姐妹

时间:2015-08-18 21:21:28

标签: javascript jquery html

所以我有一个问题,我确实知道解决方案,但在这个过程中需要大量的重复代码,所以我知道必须有一个更简单的方法来做到这一点。我有一个div列表,都有一个主图像和alt图像。 alt图像隐藏在主图像后面,当用户将鼠标悬停在主图像上时,它们应该相互切换。每个div都有自己的特定ID,但我真的不想一次又一次地编写相同的脚本来改变ID。这是我的HTML(简化但相同的结构减去绒毛):

<section>
    <div id="one">
         <img src="#" class="main" />
         <img src="##" class="alt" style="display: none;" />
    </div>
    <div id="two">
         <img src="#" class="main" />
         <img src="##" class="alt" style="display: none;" />
    </div>
    <div id="three">
         <img src="#" class="main" />
         <img src="##" class="alt" style="display: none;" />
    </div>
</section>

和我写的jQuery:

<script type="text/javascript">
    $(document).ready(function () {
        $('#one img.main').mouseenter(function () {
            $('#one img.main').hide();
            $('#one img.alt').show();
        });
        $('#one img.alt').mouseleave(function () {
            $('#one img.alt').hide();
            $('#one img.main').show();
        });
    });
</script>

我真的不想为每个div重复,因为我当前页面中有9个。有什么建议?

解决:

jQuery(document).ready(function () {
        //swap out main images on hover
        jQuery('.stores div img.main').mouseenter(function () {
            jQuery(this).hide();
            jQuery(this).next('img.alt').show();
        });
        jQuery('.stores div').mouseleave(function () {
            jQuery('img.alt').hide();
            jQuery('img.main').show();
        });
    });

4 个答案:

答案 0 :(得分:1)

您应该能够将其缩减为:

$(document).ready(function () {
    $('section > div > img.main').mouseenter(function () {
        $(this).hide();
        $(this).next('img.alt').show();
    });
    $('section > div > img.alt').mouseleave(function () {
        $(this).hide();
        $(this).prev('img.main').show();
    });
});

答案 1 :(得分:0)

您可以为每个第一个img使用此选择器:

$('section div img:first')

所以如果你在一节中加上一个id:

$('#yourSectionId div img:first')

答案 2 :(得分:0)

你需要在div上编写脚本mouseenter和div本身的mouseleave

<script type="text/javascript">
    $(document).ready(function () {
        $('section > div > img.main').on('mouseenter', function (e) {
            $(this).find('~ .alt').show();
            $(this).hide();
        });
        $('section > div').on('mouseleave', function (e) {
            $(this).find('.alt').hide();
            $(this).find('.main').show();
        });
    });
</script>

答案 3 :(得分:0)

我会用:

<script>
    $(document).ready(function () {
        $('section > div').on('mouseenter', function () {
            var el = $(this);
            el.find('.main').hide();
            el.find('.alt').show();
        });
        $('section > div').on('mouseleave', function () {
            var el = $(this);
            el.find('.alt').hide();
            el.find('.main').show();
        });
    });
</script>
相关问题