jQuery-悬停时更改图片src [英] jQuery - Change image src on hover
本文介绍了jQuery-悬停时更改图片src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上我想更改图像src以在悬停时添加-active.png
.
Basically I want to change the image src to add -active.png
on hover.
因此,fb.png悬停时将变为fb-active.png,不悬停时将变为fb.png.
So fb.png would become fb-active.png on hover, and fb.png when it's not hovering.
我不太确定自己在做什么错,所以到目前为止我将发布代码:-
I'm not too sure what I am doing wrong so I'll post my code so far:-
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的情况下完成. 像这样:
This can be done without javascript, with only css. Like this:
为图标提供不同的类,例如fb
用于Facebook,tw
或Twitter等.
Give different classes for icons like fb
for facebook,tw
or twitter and so on.
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");}
您可以使用Sprite来提高效率.
You can use sprite for efficiency.
这篇关于jQuery-悬停时更改图片src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文