问题
I'm trying to use CSS transitions to make a background image fade in on my menu when you hover over it. I want it to take about 2 seconds to fade it. It works perfectly in Firefox but all on other browsers it just appears instantly. In IE it doesn't work at all but I'm not worried about that since I never expected it to work.
CSS LAYOUT
.mainmenu ul li{
height: 86px;
display: inline-block;
margin: 0;
padding: 0;
z-index:1000;
position: relative;
}
.mainmenu li:after{
content: "";
opacity: 0;
-webkit-transition: opacity 1.5s;
-moz-transition: opacity 1.5s;
-o-transition: opacity 1.5s;
-ms-transition: opacity 1.5s;
transition: opacity 1.5s;
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
}
.mainmenu li:hover:after{
opacity: 1;
}
CSS APPEARANCE
.mainmenu li:after{
background: url(../images/hover.png) no-repeat center bottom;
}
HTML
<div class="mainmenu"><ul><li><a href=''>Home</a></li><li><a href=''>About Us</a></li><li><a href=''>Contact Us</a></li><li><a href=''>Blog</a></li><li><a href=''>Gallery</a></li></ul></div>
Can anyone help? Apart from IE it does work it making the image appear but it would be nice to get the fade in working on Chrome, Safari and Opera. If I can get it working then, I might even be able to think about IE.
回答1:
As @Tyriar states, support for transitions/animations on generated content is patchy. It works for me in the latest Chrome Canary (Version 27.0.1444.3), so very soon it will be on the regular channel. When that lands, this will be supported in IE10, Firefox 4+ and Chrome. There's the notable exception of Safari (and Opera, but with the move to WebKit that might change).
The most robust solution for now will be to avoid trying to transition the :after
content and instead apply it to one of your existing elements. That will get you pretty good browser support at 68%.
Here's a fork of your original example. Rather than using generated content, I've simplified the CSS to this:
.mainmenu li {
position: relative;
display: inline-block;
height: 86px;
margin: 0;
padding: 0;
background: url(http://placekitten.com/g/100/100) no-repeat center bottom;
}
.mainmenu li a {
position: relative;
display: block;
height: 100%;
background: #fff;
transition: all 1.5s ease-in-out;
}
.mainmenu li a:hover {
background: transparent;
}
Here, the transition is on the a
itself, fading that from white to transparent to achieve the same effect.
回答2:
As mentioned, CSS transitions on :psuedo
elements doesn't have the greatest support.
http://css-tricks.com/transitions-and-animations-on-css-generated-content/
With straight html/css you can do this, but you'll need to slap in an additional element, here's a quick fiddle : http://jsfiddle.net/9uwVb/
来源:https://stackoverflow.com/questions/15499422/css-transition-only-working-in-firefox