问题
Please view this code jsfiddle: http://jsfiddle.net/rflfn/6wCp6/
<div id="menu">
<ul>
<li><a href="#">Link #1</a></li>
<li><a href="#">Link #2</a></li>
<li><a href="#">Link #3</a></li>
<li><a href="#">Link #4</a></li>
</ul>
</div>
CSS:
*{
margin: 0;
padding: 0;
text-decoration: none;
font-family: arial;
font-size: 16px;
}
a{
color: #000000;
}
a:hover{
color: #860000;
}
#menu{
margin: 15px auto;
padding: 20px;
width: 300px;
background: #DDDDDD;
border-radius: 5px;
box-shadow: 0 0 5px #000000;
}
#menu ul{
list-style: none;
}
#menu li:before{
margin-right: 10px;
content: url("http://st.deviantart.net/emoticons/s/smile.gif");
transition: all 0.5s ease 0s;
/* transition: content 0.5s ease 0s; */
}
#menu li:hover:before{
content: url("http://st.deviantart.net/emoticons/r/razz.gif");
}
I have one image on tag 'li' and other image on 'li:hover', is possible make transition with fade only using css?
回答1:
You can do this by using both pseudo elements :before/after
and using the CSS3 transition to animate the opacity of both on hover. This will create a fade transition between both images.
DEMO
CSS :
*{
margin: 0;
padding: 0;
text-decoration: none;
font-family: arial;
font-size: 16px;
}
a{
color: #000000;
}
a:hover{
color: #860000;
}
#menu{
margin: 15px auto;
padding: 20px;
width: 300px;
background: #DDDDDD;
border-radius: 5px;
box-shadow: 0 0 5px #000000;
}
#menu ul{
list-style: none;
}
#menu ul li{
position:relative;
}
#menu li:before{
margin-right: 10px;
content: url("http://st.deviantart.net/emoticons/s/smile.gif");
transition: opacity 0.5s ease;
-webkit-transition: opacity 0.5s ease;
}
#menu li:after{
content: url("http://st.deviantart.net/emoticons/r/razz.gif");
position:absolute;
left:0;
opacity:0;
transition: opacity 0.5s ease;
-webkit-transition: opacity 0.5s ease;
}
#menu li:hover:after{
opacity:1;
}
#menu li:hover:before{
opacity:0;
}
EDIT :
Even better, you can position both images one on top of the other and with z-index and css transition animate the opacity of ony one image :
DEMO
回答2:
I think @web-tiki 's answer suits your needs and it's simpler. But just to show another possible solution:
You can separate the icons in two elements, each with its own content. Then, apply the transition on the li:hover
event, setting the element's opacity inverted. Like this example:
FIDDLE: http://jsfiddle.net/2J7b9/1/
<ul>
<li>
<div class="img1"></div>
<div class="img2"></div>
test
</li>
</ul>
CSS:
li {
position: relative;
padding-left: 30px;
}
li .img1, li .img2 {
position: absolute;
top: 0;
left: 0;
}
li .img1 {
opacity: 1;
transition: all .25s ease-in-out;
}
li .img2 {
opacity: 0;
transition: all .25s ease-in-out;
}
li .img1:before {
content: url("http://st.deviantart.net/emoticons/s/smile.gif");;
}
li .img2:before {
content: url("http://st.deviantart.net/emoticons/r/razz.gif");
}
li:hover .img1 {
opacity: 0;
}
li:hover .img2 {
opacity: 1;
}
来源:https://stackoverflow.com/questions/23938088/is-possible-use-fade-transition-on-tag-content-only-with-css