【问题标题】:Move background image up and down上下移动背景图像
【发布时间】:2014-03-24 20:05:22
【问题描述】:

我有一个带有背景图片的 div。如何做到这一点:当您将鼠标悬停在该 div 上时,背景图像向上移动 5 像素,然后向下移动 5 像素?例如快点,慢点。

我的代码:

CSS

<style>
.place {
background:url(../img/place.png) no-repeat 6px 50%;
}
</style>

HTML

 <div class="place">
    123 Something Street<br/>
    UB5 212 Liverpool
    </div>

如何通过过渡做到这一点?还是 jquery?

【问题讨论】:

  • 试过类似position:fixed
  • 为什么要改变页面结构以获得简单的效果?我认为 CSS3 能够做到这一点。我不认为目前广泛支持背景的 CSS3 动画,所以可能需要 jQuery。

标签: jquery css transition


【解决方案1】:

使用 CSS3

.place {
    background:url(http://lorempixel.com/20/20/) no-repeat;
}

div.place:hover {
    animation:myanim 0.5s;
    -webkit-animation:myanim 0.5s;
    /* Safari and Chrome */
}

@keyframes myanim {
    0% {
        background-position:0 0;
    }
    50% {
        background-position:20px 0;
    }
    100% {
        background-position:0 0;
    }
}

@-webkit-keyframes myanim
/* Safari and Chrome */
 {
    0% {
        background-position:0 0;
    }
    50% {
        background-position:20px 0;
    }
    100% {
        background-position:0 0;
    }
}

【讨论】:

  • 这是有效的,但是当它向下移动时,最后的动画不流畅。
【解决方案2】:

.animate() 用于background-position 属性:

    $('div.place').on('hover', function() {
      $(this).animate({
         'background-position-y': '15px'
      }, 500, 'linear');
   });

【讨论】:

    【解决方案3】:

    你也可以试试 CSS3:

       transition: background-position 1s ease;
       -moz-transition: background-position 1s ease; /* Firefox */
       -webkit-transition: background-position 1s ease; /* Safari and Chrome */
    

    【讨论】:

    • 添加div.place:hover选择器
    【解决方案4】:

    所有你需要添加background-position 样式到你的 div 背景并做一些 jQuery 小东西:

    1. 添加到 CSS:

      背景位置:10px 10px;

    2. 并准备好 jQuery:

      $('.place').hover(function(){ $('.place').css('背景位置', '10px 5px'); 设置超时(函数(){ $('.place').css('背景位置', '10px 10px');
      }, 2000); });

    Here is the working example

    【讨论】:

    • 使用这些 jsfiddles,它们需要永远加载,并且很少工作。投票 1 关闭 jsfiddels。
    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多