【问题标题】:Background color "animation" with jQueryjQuery的背景颜色“动画”
【发布时间】:2011-10-11 01:38:59
【问题描述】:

我正在尝试创建一个简单的动画,其中背景颜色滑动到位。到目前为止它是成功的,但有一个主要问题:块上的文字移动,我不知道如何阻止它。

我可以将文本放在上面,但我还需要更改颜色,如果我在 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/

【问题讨论】:

    标签: jquery css jquery-animate


    【解决方案1】:

    两件事:

    1. http://jsfiddle.net/WERFJ/13/ 可能需要稍作调整,但这就是您想要的效果。基本上我只是将文本从 h1 中取出并在其上放置一个 z-index,使其始终位于前面,然后使用 .button:hover span { color: #000 }

    2. 使用 h1 来执行此操作不是正确使用 h1。我只会使用常规的 div。

    【讨论】:

      【解决方案2】:

      你可以把文字放在它唯一的层上:

      <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/

      【讨论】:

        猜你喜欢
        • 2023-03-11
        • 2010-09-16
        • 1970-01-01
        • 2010-11-20
        • 1970-01-01
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        • 2020-11-04
        相关资源
        最近更新 更多