简体   繁体   中英

Change Image on mouse hover and mouse out in CSS

I use below mention code to produce a CSS transition effect. A div shows first image (ie 1.jpg), and upon mouse-hover the second image (2.jpg) is appear through CSS transition and when mouse-out the first image is back to display.

I need a third image on mouse-out so kindly help me how i do this through CSS.
My coding is as under:

.mainimg
{
    background-image:url(1.jpg);
    height: 300px;
    width: 300px;
    transition: 1s;
}
.img2
{
    background-image:url(2.jpg);
    background-size:500px 500px;
    width:0px;
    height:300px;
    transition:1s
}
.mainimg:hover .img2
{
    width:300px;
    transition:1s;
}   
<div class="mainimg">

<div class="img2"></div>
 </div>

Try this out: use the same div for containing image

<div class="mainimg">

and use css hover to change image background

.mainimg {
  background-image:url(1.jpg);
  height: 300px;
  width: 300px;
  transition: 1s;
}
.mainimg:hover {
  background-image:url(2.jpg);
  transition: 1s;
}

The rollover is state is binary in CSS, an element is either being hovered over or it is not. You will need to use JavaScript for doing what you want.

what @Franz Thüs says is correct you have to use Javascript for the 3e image. also what @Med7at is saying try using one div and change the image via the :hover

this should work for you.

I used an id instead of an class so only one item will change with those images.

i used colors so you can see the differents.

 var mouseOut = document.getElementById("mainimg"); mouseOut.onmouseout = function() { this.style.backgroundColor = "orange"; //this.style.background = "url(3.jpg)" } 
 #mainimg{ background:blue; /*background-image:url(1.jpg);*/ height: 300px; width: 300px; transition: 1s; } #mainimg:hover{ background:red; /*background-image:url(2.jpg);*/ background-size:500px 500px; /* this will make the 3 img look missplaced for 1 second. } 
 <div id="mainimg"></div> 

see the comments what you should put in that line to make it work with the images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM