2011-10-11 115 views
1

我试图创建一个简单的动画,其中的背景颜色滑入到位。到目前为止,它是成功的,但有一个主要问题:块上的文本移动,我无法弄清楚如何阻止它。jQuery的背景颜色“动画”

我可以定位上面的文本,但我需要改变颜色,如果我在jQuery中这样做,它会创建一个混乱。

的CSS:

.button { 
    display: block; 
    width: 130px; 
    height: 40px; 
    cursor: pointer; 
    position: fixed; 
    z-index: 1; 
    top: 15px; 
    left: 15px; 
    text-align: center; 
    color: #FFF; 
    overflow: hidden; 
    text-decoration: none; 
    font-size: 23px; 
    text-transform: lowercase; 
    font-family: Helvetica, Arial, sans-serif; 
    background: #FFF 
} .button:hover { color: #FFF } 
.button h1 { 
    display: inline-block; 
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 130px; 
    height: 40px; 
    font-size: 23px; 
    margin: 0; 
    background-color: blue 
} 
.button h1.back { 
    z-index: 999; 
    color: #000; 
    margin-left: -130px; 
    overflow: hidden; 
    background-color: red 
} 
.button h1 span { 
    position: absolute; 
    left: 0; 
    top: 10%; 
    width: 130px; 
    height: 40px; 
    text-align: center 
} 

然后jQuery的:

$('.button').hover(function() { 
    var el = $(this); 
    el.children('.back').animate({ 
     marginLeft: '0' 
    }, 30, 'swing'); 
}, function() { 
    var el = $(this); 
    el.children('.back').animate({ 
     marginLeft: '-130px' 
    }, 30, 'swing'); 
}); 

它创造了一个伟大的动画。但是文字,它随着它滑动。我怎样才能防止这种没有毛病颜色变化?

这里是的jsfiddle:http://jsfiddle.net/WERFJ/

回答

2

两件事情:

  1. http://jsfiddle.net/WERFJ/13/它可能需要一些调整,但是这是你后的效果。基本上我只是把文本从h1中取出,并在其上放置了一个z-index,所以它始终在前面,然后用.button:hover span { color: #000 }

  2. 使用h1's来做到这一点不是h1的正确用法。我只会使用普通的div。

+0

工作,谢谢。 –

0

你可以把文字上,这只是层:

<a href="#" class="button"> 
    <h1 class="front"><span></span></h1> 
    <h1 class="back"><span></span></h1> 
    <h1 class="text"><span>hello</span></h1> 
</a> 

http://jsfiddle.net/WERFJ/14/

也许与完整的文本效果:

$(function() { 
    var $text = $('.text'); 
    $('.button').hover(function() { 
     $(this).children('.back').animate({ 
      marginLeft: '0', 
     }, 100, 'swing', function(){ 
      $text.css('color','white'); 
     }); 
    }, function() { 
     $(this).children('.back').animate({ 
      marginLeft: '-130px' 
     }, 100, 'swing', function(){ 
      $text.css('color','black'); 
     }); 
    }); 

}); 

http://jsfiddle.net/WERFJ/17/