Javascript悬停图片替换

时间:2011-01-13 05:57:16

标签: javascript jquery image hover

我有一些社交媒体图标,我想在它们徘徊时改变颜色。我认为最简单的方法是用新的替换图像(它们是小的png文件)。你有什么建议?动态函数是理想的..有四个图标,每个图标的文件名为demo.png,demo_hover.png。我正在使用jQuery库。

谢谢!

HTML

  <a class="a" id="interscope_icon" href="http://www.interscope.com/" alt="Interscope Records" target="_blank"><img class="icon" id="interscope" src="../Images/icons/interscope.png" alt="Interscope Records" /></a>
  <a class="a" href="http://www.twitter.com/FernandoGaribay" alt="Twitter" target="_blank"><img class="icon" id="twitter" src="../Images/icons/twitter.png" alt="Fernando Garibay's Twitter" /></a>
</p>
<p>
  <a class="a" href="http://www.facebook.com/f2inc" alt="Facebook" target="_blank"><img class="icon" id="facebook" src="../Images/icons/facebook.png" alt="Fernando Garibay's Facebook" /></a>
  <a class="a" href="http://www.myspace.com/f2inc" alt="Myspace" target="_blank"><img class="icon" id="myspace" src="../Images/icons/myspace.png" alt="Fernando Garibay's Myspace" /></a>
</p>

的jQuery

$('#interscope_icon').hover(function(){
  $('#interscope').attr('src', 'Images/icons/interscope.png');
});

4 个答案:

答案 0 :(得分:6)

你可能最好使用'CSS sprite'方法而不是加载新图像......

http://css-tricks.com/css-sprites/

答案 1 :(得分:2)

简单的方法是用CSS方式:

#interscope_icon { background-image: url(...) }
#interscope_icon:hover { background-image: url(...) }

答案 2 :(得分:1)

我也遇到了这种困境所以想出了自己的方法。超级简单,效果很好,不需要精灵,只需一个透明的PNG:

HTML:

<div class="facebookicon">
    <a href="#!"><img src="http://example.com/some.png"></a>
</div>

CSS:

.facebookicon img {
    background: #fff;
    transition:  background 400ms ease-out;
}

.facebookicon img:hover {
    background: #3CC;
    transition:  background 400ms ease-in;
}
/* you need to add various browser prefixes to transition */
/* stripped for brevity */

http://jsfiddle.net/mattmagi/MpxBd/

让我知道你的想法。

答案 3 :(得分:0)

我会将锚点(background-image)上的社交图标设为display: inline-block;,而不是锚点内的<img />元素。

然后简单地定义一个a:hover状态,将CSS更改为不同的背景。也许甚至精灵都可以。

这样的事情:

#some_id { background-image: url(...); }
#some_id:hover { background-image: url(...); }