How do I do flickerless image switch on hover with CSS only?
The code is as follows:
<div id="compv-navbar">
<a href="#"><img src="image1.png" id="icon1"开发者_C百科></a> |
<a href="#"><img src="image2.png" id="icon2"></a> |
<a href="#"><img src="image3.png" id="icon3"></a> |
<span id="view_name"> Random Text</span>
</div>
Assume that each image has another image with suffix '-hover' that will be image to be replaced on hover.
Here is what i would do:
<div id="compv-navbar">
<a href="#" id="icon1"></a> |
<a href="#" id="icon2"></a> |
<a href="#" id="icon3"></a> |
<span id="view_name"> Random Text</span>
</div>
a#icon1{
background:url("image1.png") no-repeat;
}
a:hover#icon1{
background:url("image1-hover.png") no-repeat;
}
a#icon2{
background:url("image2.png") no-repeat;
}
a:hover#icon2{
background:url("image2-hover.png") no-repeat;
}
a#icon3{
background:url("image3.png") no-repeat;
}
a:hover#icon3{
background:url("image3-hover.png") no-repeat;
}
CSS isn't meant to do this, it controls presentation, not the location of files. If you really need this however, here's a little work-around they should work (I haven't actually tested this yet).
HTML
<div id="compv-navbar">
<a href="#"><span id="icon1"></span></a> |
<a href="#"><span id="icon2"></span></a> |
<a href="#"><span id="icon3"></span></a> |
<span id="view_name"> Random Text</span>
</div>
CSS
#icon1
{
width:100px; /*Change this to your image width*/
height:100px; /*Change this to your image width*/
background-image:url("image1.png");
}
#icon1:hover
{
width:100px; /*Change this to your image width*/
height:100px; /*Change this to your image width*/
background-image:url("image1-hover.png");
}
(Make sure you add this for each image.)
Well, totally flickerless image switch you can do only with image preloading. In any other case browser will load image only on hover. I wrote a small example about image switching.
Another solution is to use CSS sprites and switch image on hover using background-position
.
精彩评论