简体   繁体   English

在CSS上的鼠标悬停和鼠标移出时更改图像

[英]Change Image on mouse hover and mouse out in CSS

I use below mention code to produce a CSS transition effect. 我使用下面提到的代码来产生CSS过渡效果。 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. div显示第一个图像(即1.jpg),鼠标悬停时,第二个图像(2.jpg)通过CSS过渡出现,并且当鼠标移出时,第一个图像重新显示。

I need a third image on mouse-out so kindly help me how i do this through CSS. 我需要鼠标移出时的第三张图像,因此请帮助我如何通过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包含图像

<div class="mainimg">

and use css hover to change image background 并使用css悬停更改图像背景

.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. 过渡状态是CSS中的二进制状态,元素是否已悬停或未悬停。 You will need to use JavaScript for doing what you want. 您将需要使用JavaScript进行所需的操作。

what @Franz Thüs says is correct you have to use Javascript for the 3e image. @FranzThüs说的是正确的,您必须对3e图像使用Javascript。 also what @Med7at is saying try using one div and change the image via the :hover @ Med7at所说的也是尝试使用一个div并通过:hover更改图像

this should work for you. 这应该为您工作。

I used an id instead of an class so only one item will change with those images. 我使用id而不是class因此这些图像只会更改一项。

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. 查看注释,您应该在该行中添加些内容以使其与图像配合使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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