如何通过CSS3动画淡入背景图像

问题描述 投票:0回答:1

我正在制作一个菜单,每个项目都有一个文本,如项目 1、项目 2 等。悬停时背景颜色会发生变化,文本会变得透明,背景图像会被替换。我使用这段代码来缓入和缓出样式。但它仅适用于背景颜色,不适用于图像。

#nav li:hover {
    color:transparent !important;
    text-shadow: none;
    background-color: rgba(255, 0, 0, .5);

    -webkit-transition: all 1s ease-in;
    -moz-transition: all 1s ease-in;
    -o-transition: all 1s ease-in;
    -ms-transition: all 1s ease-in;
    transition: all 1s ease-in;
}

这是在线版本: http://jsfiddle.net/q4uHz/

css animation background-image css-transitions css-animations
1个回答
10
投票

背景图片不能动画;没有算法可以做到这一点。一个简单的解决方案是在 HTML 中包含

<img>
和图标,而不是
opacity: 0
并为其设置动画。类似的东西。

<li id="home">
<img src="http://cdn3.iconfinder.com/data/icons/picons-social/57/16-apple-48.png">
<a href="#home">Home</a></li>

#nav li {
    position: relative;
}
#nav li img {
    opacity: 0;
    position: absolute;
    transition: all 1s ease-in;
    top: 0;
    left: 0;
}
#nav li:hover img {
    opacity: 1;
}

#nav {
    font: 14px 'LeagueGothicRegular', Arial, sans-serif;
    color: #f9f8cc;
    width:300px;
    clear: both;
    height: 58px;
    margin: 5px 0px 0px 50px;
    background:#c2c2c2;
    opacity:.8;
}

#nav ul {
    margin: 0;
    padding: 0;
}
#nav li {
    list-style-type: none;
    background-image: none;
    color: #FDE99D;
    float: left;
    height:48px; width:85px;
    border-right:1px #333333 solid;
    text-align:center;
    padding-top:10px;
    position: relative;
    
    -webkit-transition: all 1s ease-out;
    -moz-transition: all 1s ease-out;
    -o-transition: all 1s ease-out;
    -ms-transition: all 1s ease-out;
    transition: all 1s ease-out;
}

#nav li a {
    color: #000;
    text-shadow: 0px 2px 2px #222;
    text-transform: uppercase;
}

#nav li:hover a {
    color: #999;
    color:transparent !important;
    text-shadow: none;
    
}

#nav li:hover {
    color:transparent !important;
    text-shadow: none;
    background-color: rgba(255, 0, 0, .5);
    
    -webkit-transition: all 1s ease-in;
    -moz-transition: all 1s ease-in;
    -o-transition: all 1s ease-in;
    -ms-transition: all 1s ease-in;
    transition: all 1s ease-in;
}
#nav li img {
    opacity: 0;
    position: absolute;
    transition: all 1s ease-in;
    top: 0;
    left: 0;
}
#nav li:hover img {
    opacity: 1;
}
<div id="nav">
    <ul>
     <li id="home">
         <img src="http://cdn3.iconfinder.com/data/icons/picons-social/57/16-apple-48.png">
         <a href="#home">Home</a></li>
     <li id="item1">
         <img src="http://cdn3.iconfinder.com/data/icons/picons-social/57/16-apple-48.png">
         <a href="#contact">Contact</a></li>
      
    </ul>
  </div>

© www.soinside.com 2019 - 2024. All rights reserved.