开发者

Javascript hover image replacement

I've got some social media icons that I'd like to change color when they're hovered over. I figured the easiest way to do this is by replacing the image with a new one (they're small png files). What do you suggest? A dynamic function would be ideal.. there are four icons, each of which has a filename of demo.png, demo_hover.p开发者_开发百科ng. I'm using the jQuery library.

Thank you!

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');
});


You're probably better off using the 'CSS sprite' method rather than loading a new image...

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


The easy way is to do it the CSS way:

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


I just had this dilemma as well so came up with my own method. Super easy, works great and no need for sprites, just an transparent 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/

Let me know what you think.


I would give the social icons as the background-image on the anchors (with display: inline-block;) instead of as <img /> elements inside the anchors.

Then simply define an a:hover state that changes the CSS to a different background. Perhaps even sprite them.

Something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜