jQuery – 在悬停时更改图像src

基本上我想在悬停时将图像src更改为add -active.png.

所以fb.png在悬停时会变成fb-active.png,而在没有悬停时变成fb.png.

我不太确定我做错了什么,所以到目前为止我会发布我的代码: –

HTML

<div id="main-contact" class="right">

            <div id="main-social">

                <a href="#!"><img class="img-social" alt="Company - Facebook" class="left" src="images/fb.png" /></a>

                <a href="#!"><img class="img-social" alt="Company - Twitter" class="left" src="images/twitter.png" /></a>

                <a href="#!"><img class="img-social" alt="Company - LinkedIn" class="left" src="images/linkedin.png" /></a>

                <a href="#!"><img class="img-social" alt="Company - Word Press" class="left" src="images/wordpress.png" /></a>               

            </div>

        </div>

jQuery的

$(document).ready(function() {

$(function(){
    var regexactive = /-active\..*$/;

    var ct = $('#main-social');
    var imgs = $('.img-social img', ct);

    function activateImage(imgs){
        imgs.each(function(){
            var img = $(this);
            var src = img.attr('src');
            if( !regexactive.test(src) ){
                img.attr('src', src.replace('.png', '-active.png'))
            }
        });
    }

    ct.on('hover', '.img-social', function(){


        var img = $('.img-social img');
        activateImage(img);
    });
});

});
这可以在没有javascript的情况下完成,只有css.
像这样:

为facebook,tw或twitter等fb等图标提供不同的类.

HTML:

<div id="main-social">    
    <a href="#!"><span class="img-social fb left" title="Company - Facebook"></span></a>
    <a href="#!"><span class="img-social tw left" title="Company - Twitter"></span></a>
    <a href="#!"><span class="img-social ln left" title="Company - LinkedIn"></span></a> 
    <a href="#!"><span class="img-social wp left" title="Company - Word Press"></span></a> 
</div>

CSS:

.img-social{display:inline-block;height:20px;width:20px;}
.fb{background:url("images/fb.png");}
.fb:hover{background:url("images/fb-active.png");}
.tw{background:url("images/twitter.png");}
.tw:hover{background:url("images/twitter-active.png");}
.ln{background:url("images/linkedin.png");}
.ln:hover{background:url("images/linkedin-active.png");}
.wp{background:url("images/wordpress.png");}
.wp:hover{background:url("images/wordpress-active.png");}

您可以使用精灵来提高效率.

相关文章
相关标签/搜索