简体   繁体   English

在悬停时将图像转换为另一个图像

[英]transition of image to another image on hover

I want transition of image to another image when hover. 我希望在悬停时将图像转换为另一个图像。 But after using the following code the size of the image is more than the page and when hover the image disappears and no other image can be seen. 但使用以下代码后,图像的大小超过页面,当悬停时图像消失,无法看到其他图像。

HTML HTML

<html>
    <head>
     <title></title>
     </head>
    <body>
      <div id="cssfade">
       <img src="image1.jpg" height:200px;width:300px;/>
       </div>
    </body>
</html>

CSS CSS

#cssfade { 
    background-image: url('image2.jpg');
    height:200px; 
    width: 300px;
}
#cssfade img {
    -webkit-transition: all ease 1s;
    -moz-transition: all ease 1s;
    -o-transition: all ease 1s;
    -ms-transition: all ease 1s;
    transition: all ease 1s;
}
#cssfade img:hover {
    opacity:0;
}

I'm assuming the image in the div is content so I have left it there and merely moved the hover to take effect when the wrapping div is hovered. 我假设div中的图像是内容所以我把它留在那里只是移动悬停以在包装div悬停时生效。

 #cssfade { width: 300px; height: 200px; background-image: url(http://lorempixel.com/300/200/sports/2/); } #cssfade img { width: 300px; height: 200px; display: block; transition: opacity 1s ease; } #cssfade:hover img { opacity: 0; } 
 <div id="cssfade"> <img src="http://lorempixel.com/300/200/sports/1/" alt=""> </div> 

Use background-image on div . div上使用background-image

On hover change the background-image . hover更改background-image

Transition: 过渡:

MDN CSS Tricks MDN CSS技巧

Demo 演示

 #cssfade { background-image: url('http://lorempixel.com/400/200'); height: 200px; width: 300px; } #cssfade:hover { -webkit-transition: all ease 1s; -moz-transition: all ease 1s; -o-transition: all ease 1s; -ms-transition: all ease 1s; transition: all ease 1s; background-image: url('http://lorempixel.com/400/200/sports/1'); } 
 <div id="cssfade"></div> 

EDIT - Just to clarify the difference to Tushar 's answer, the transitions should be on #cssfade rather than #cssfade:hover to ensure the transition applies when hovering and un-hovering. 编辑 - 只是为了澄清与Tushar的答案的区别,转换应该在#cssfade而不是#cssfade:hover以确保在悬停取消悬停时应用转换。

HTML: HTML:

<html>
  <head>
    <title>...</title>
  </head>
  <body>
    <div id="cssfade"></div>
  </body>
</html>

CSS: CSS:

#cssfade { 
  height:200px; 
  width: 300px;
  background-image: url('image1.jpg') no-repeat;
  -webkit-transition: all ease 1s;
  -moz-transition: all ease 1s;
  -o-transition: all ease 1s;
  -ms-transition: all ease 1s;
  transition: all ease 1s;
}

#cssfade:hover {
  background-image: url('image2.jpg') no-repeat;
}

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

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