CSS 如何使用 css3 动画更改背景位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7276620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 01:29:37  来源:igfitidea点击:

How do I change a background position with css3 animation?

animationcssbackground-positionkeyframe

提问by fenerlitk

Lets say I have a div element, with a background in position: 0%;how would I change the position to e.g position: 100%;but with keyframes on hover

假设我有一个 div 元素,背景是position: 0%;我如何将位置更改为例如position: 100%;但悬停关键帧

I can't seem to use keyframes properly, it never works and I have all the latest browsers.

我似乎无法正确使用关键帧,它永远无法工作,而且我拥有所有最新的浏览器。

Thanks.

谢谢。

回答by DuMaurier

If you just want to animate background position on hover it's a lot easier to use a transition instead of keyframe animations. See this fiddle for an example: http://jsfiddle.net/hfXSs/

如果您只想在悬停时为背景位置设置动画,则使用过渡而不是关键帧动画要容易得多。以这个小提琴为例:http: //jsfiddle.net/hfXSs/

If you want to put in the extra effort of making it an animation you'll have to set the animation-play-state on the div to 'paused' and change it to 'running' on hover. See the spec on pausing animations here: http://dev.w3.org/csswg/css3-animations/#the-animation-play-state-property-

如果您想付出额外的努力使其成为动画,您必须将 div 上的动画播放状态设置为“暂停”并在悬停时将其更改为“运行”。在此处查看有关暂停动画的规范:http: //dev.w3.org/csswg/css3-animations/#the-animation-play-state-property-

EDIT: I was bored so here's the same thing using keyframe animations: http://jsfiddle.net/wGRg5/

编辑:我很无聊,所以这里使用关键帧动画是同样的事情:http: //jsfiddle.net/wGRg5/

Obviously, the fiddle has the problem that when you aren't hovering over the div the animation pauses which is probably not the desired effect.

显然,小提琴有一个问题,即当您没有将鼠标悬停在 div 上时,动画会暂停,这可能不是您想要的效果。

回答by Foxinni

Some Code, looks like webkit only at this point in time.

一些代码,只是在这个时间点看起来像 webkit。

.box {
    display:block;
    height:300px;
    width:300px;
    background:url('http://lorempixum.com/300/300') no-repeat;
    background-position:-300px;
    -webkit-transition:background-position 1s ease;
}

.box:hover{
    background-position:0px;
}

Via: http://jsfiddle.net/hfXSs/

通过:http: //jsfiddle.net/hfXSs/

More here: http://css-tricks.com/parallax-background-css3/

更多信息:http: //css-tricks.com/parallax-background-css3/