CSS3过渡效果在背景图片上的应用

12

我想在背景图像上执行CSS3变换:rotate(360deg),并在1秒的过渡内完成。是否可能?我已经在Google上搜索了很多但没有成功!我的目标是实现类似于:

#footerLogo { 
  background: url('ster.png'), 
  -moz-transition: -moz-transform 1s,
  transition: transform 1s,
  -o-transition: -o-transform 1s,
  -webkit-transition: -webkit-transform 1s;
  background-position: #outlinedtotheleft;
}
#footerLogo:hover {
  background: transform: rotate(360deg);
  -o-transform: rotate(360deg);
  -moz-transform: rotate(360deg);
  -webkit-transform: rotate(360deg);
}

希望这是可能的!我知道可以很容易地在JS(jQuery)中完成:

$('#something').hover(function(){morecodehere});
...但我想知道是否仅使用CSS(3)也可以实现。

HTML:

<div id="footerLogo">
  <img src="carenza.png"/>
</div>

下次添加代码块时,只需将整个块缩进4个或更多空格以保留缩进。使用反引号表示行内代码。 - numbers1311407
2个回答

13
当然可以,试试像这样做:
HTML
<div id="planet">
</div>

CSS

#planet { 
    width:200px;
    height:200px;
    background: transparent url(http://cdn3.iconfinder.com/data/icons/nx11/Internet%20-%20Real.png) no-repeat center center;
}

#planet {
  -webkit-animation-name: rotate;
  -webkit-animation-duration:2s;
  -webkit-animation-iteration-count:infinite;
  -webkit-animation-timing-function:linear;
  -moz-animation-name: rotate;
  -moz-animation-duration:2s;
  -moz-animation-iteration-count:infinite;
  -moz-animation-timing-function:linear;
}

@-webkit-keyframes rotate {
  from {-webkit-transform:rotate(0deg);}
  to {  -webkit-transform:rotate(360deg);}
}

@-moz-keyframes rotate {
  from {-moz-transform:rotate(0deg);}
  to {  -moz-transform:rotate(360deg);}
}

JSFiddle


几乎可以了,但它只需要在鼠标悬停时进行转换,并且div包含另一个IMG。想象一下:您有一个小星星图像(独立但是原始标志的一部分),以及旁边的标志的其余部分(“某个名称”)。如果我悬停在div上(两个图像之一),那么只有星星会旋转。仅使用CSS3.. 不过还是很好的例子 :-)! - Dominique
现在我正在尝试编辑您的代码,以实现这样的效果:如果您的鼠标不再悬停在星形图案上,则星形图案将会旋转回到起始点。 - Dominique
使用CSS3,你无法以任何方式实现这一点(至少我不知道有什么方法)。悬停状态相当线性,不允许在悬停和非悬停之间进行过渡,你可以使用JavaScript来实现。 - Andres Ilich
是的,你可以用JS解决这个问题,但挑战在于用CSS3来实现它 ;)。我以前已经做到过;通过“onmouseout”使转换返回,但我已经得到了很多帮助,主要问题已经得到回答了(我猜?)。我想我也不能在同一个线程中问这个问题。 - Dominique
1
我认为使用任何其他类型的转换都很容易实现,比如填充,你可以通过悬停状态将填充增加10px并在活动状态下降低填充,但是对于旋转这样抽象的东西,我不认为仅凭CSS就能做到那种特定程度的控制。当然,我可能错了,毕竟我每天都会在CSS3中发现新的东西。 - Andres Ilich
做了一些额外的测试并使演示更加流畅,您可以在此处查看:http://jsfiddle.net/YqdJb/3/ ... 我省略了Firefox的供应商前缀以进行测试,请在Chrome中进行测试,稍后可以添加这些前缀。 - Andres Ilich

5

我认为你不能将变换应用于背景图像本身(与div分开)。但是,你可以旋转整个div,包括使用过渡来进行动画处理(这里有一个工作示例。)

如果你能描述你想要实现的确切效果,可能会有所帮助。

代码:

#footerlogo {
    width: 200px;
    height: 200px;
    background-image: url(http://lorempixum.com/200/200);
    -webkit-transition: -webkit-transform 1s;
    -moz-transition: -moz-transform 1s;
    transition: transform 1s;
}

#footerlogo:hover {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    transform: rotate(360deg);
}

2
未加前缀的 CSS 声明应始终放在最后!一旦标准实现就绪,您希望使用它,并且不会被浏览器特定的实现所覆盖,这可能会导致错误。 - gondo
@gondo 在2011年,我怀疑没有人能够想得那么远:) 我会改变顺序。 - Matt Gibson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接