开发者

Simple HTML5/CSS3 background image transition on mouse hover

I'm trying to understand the simplest background transition possible using only HTML5 and CSS3. Searching through stackoverflow I've learned it can be easily implemented using external libraries such as jQuery but for this project I've decided not relying on any of those.

Markup

<nav> 
  <ul> 
    <li><a id="foobar" href="http://www.google.com/search?q=foobar">Foobar</a></li>
  </ul> 
</nav> 

Styles

body {
  background: url('background-default.png'), no-repeat;
}
#foobar a:hover {
开发者_JS百科   background: url('background-hover.png'), no-repeat;
  -webkit-transition: // TODO;
  -moz-transition: // TODO;
  -o-transition: // TODO;
  -ms-transition: // TODO;
  transition: // TODO;
}


As I mentioned in my comment, you can't transition the background-image property but you can get the sort of effect you're looking for if you're willing to add extra markup and then transition the opacity. So you'll have some markup like this:

<nav>
  <ul>
    <li>
      <img src="no-icon.png">
      <img src="yes-icon.png">
      <a id="foobar" href="http://www.google.com/search?q=foobar">Foobar</a>
    </li>
  </ul>
</nav>

Then set the transition on the images, absolute position them (so they'll be like backgrounds), and hide one of them by default (I've left out the vendor extensions for clarity):

nav li img {
    position: absolute;
    transition-duration: 1.5s;
    opacity: 1;
}
nav li img:first-child {
    opacity: 0;
}

Then swap the opacity values on li:hover:

nav li:hover img {
    opacity: 0;
}
nav li:hover img:first-child {
    opacity: 1;
}

Here's a full working example. Not an ideal solution because you have to add extra markup, but it'll work.


Here's an example of the code I use to achieve this. The images are sprites which each contain normal and hover state. The trick is to add the img to both li and a, and to use opacity to change the appearance of the image. You can then use css3 transitions to make this appear smoother.

<ul id="homenav">
    <li class="h"><a href="#><span>Home</span></a></li>
    <li class="i"><a href="#"><span>Inloggen</span></a></li>
    <li class="v"><a href="#"><span>Voorbeelden</span></a></li>
</ul>

#homenav li.h, #homenav li.h a        {background-image: url('img/btn_home.gif');}
#homenav li.i, #homenav li.i a        {background-image: url('img/btn_inloggen.gif');}
#homenav li.v, #homenav li.v a        {background-image: url('img/btn_voorbeelden.jpg');}

#homenav li     {background-position: 0 170px;}
#homenav li a   {background-position: 0 0;}
#homenav li a:hover
        {opacity: 0;
        -webkit-transition: opacity .8s ease-in;
        -moz-transition: opacity .8s ease-in;
        -o-transition: opacity .8s ease-in;
        transition: opacity .8s ease-in;}

#homenav a      {display: block; height: 100%;}
#homenav a span {display: none;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜