Switch between two images in html with css
I'm working on a wordpress theme and want to switch between two thumbnail images on hover.
The code that i have looks something like this :
<a class="thumb" href="posturl"> <img src="img1.jpg" class="image1" /> <img src="img2.jpg" class=开发者_Python百科"image2" /> </a>
So now I need some css to change between image1 and image2 on hover.
And if somebody knows how i can get a fade effect with some javascript that would be greatly appreciated.
be careful when using hover if you are using large images.. browser might take a while to show the image for the first time. To avoid that try using sprites and changing the background position on hover
a.thumb
{
background-image: url(img.jpg) no-repeat 0 0;
}
a.thumb:hover
{
background-image: url(img.jpg) no-repeat -100px 0; /*set to the position of the second image*/
}
if you want some effects in js.. maybe sprites are not the best answer, it depends on the effect that you want. for that you'll need a framework like Mootools or Jquery.
Good Luck
You don't need the two <img>
tags in there, you just have to reference the images and hover state in CSS:
a.thumb
{
background-image: url(img1.jpg);
}
a.thumb:hover
{
background-image: url(img2.jpg);
}
The most basic of hover examples.
You can also use CSS sprites:
a.thumb
{
background-image: url(img1_sprite.jpg);
background-position: 0 0;
}
a.thumb:hover
{
background-image: url(img1_sprite.jpg);
background-position: -60px 0; /*see below*/
}
This shoves the background to the left where 60px is the width of your second image.
For fading images you can use CSS3 transtitions, but IE does not support this until Version 9.
First, you want to get rid of the img tags and use only css:
a:link {
background: url("img1.jpg");
}
a:hover {
background: url("img2.jpg");
}
You could use javascript but that would get very complicated, CSS3 however will have fade effects ready soon:
a:link {
background: url("img1.jpg");
-webkit-transition:background 1s ease-in;
-moz-transition:background 1s ease-in;
-o-transition:background 1s ease-in;
transition:background 1s ease-in;
}
a:hover {
background: url("img2.jpg");
}
a .image1 { display: inline; }
a .image2 { display: none; }
a:hover .image1 { display: none; }
a:hover .image2 { display: inline; }
for transition, take a look at css transitions:
http://net.tutsplus.com/tutorials/html-css-techniques/css-fundametals-css-3-transitions/
精彩评论