【问题标题】:Rotating a background image with CSS3使用 CSS3 旋转背景图像
【发布时间】:2013-03-02 04:46:09
【问题描述】:

我有一个背景图像,其中有一个指向右侧的箭头。当用户单击按钮时,选定状态会将箭头更改为向下(在我的图像精灵中使用不同的背景位置)。

是否有使用 CSS3 对其进行动画处理的方法,所以一旦单击按钮并 jQuery 为其分配一个“选定”类,它将以动画方式(仅 90 度)从右到下旋转? (最好使用带有指向右侧的箭头的单个图像/位置)

我不确定是否需要使用变换或关键动画帧。

【问题讨论】:

标签: css rotation background-image css-animations


【解决方案1】:

您可以使用::after(或::beforepseudo-element,来生成动画

div /*some irrelevant css */
{
    background:-webkit-linear-gradient(top,orange,orangered);
    background:-moz-linear-gradient(top,orange,orangered);
    float:left;padding:10px 20px;color:white;text-shadow:0 1px black;
    font-size:20px;font-family:sans-serif;border:1px orangered solid;
    border-radius:5px;cursor:pointer;
}

/* element to animate */
div::after               /* you will use for example "a::after" */
{
    content:' ►';        /* instead of content you could use a bgimage here */
    float:right;
    margin:0 0 0 10px;
    -moz-transition:0.5s all;
    -webkit-transition:0.5s all;
}

/* actual animation */
div:hover::after         /* you will use for example "a.selected::after" */
{
    -moz-transform:rotate(90deg);
    -webkit-transform:rotate(90deg);
}

HTML:

<div>Test button</div>

在您的情况下,您将使用 element.selected 类而不是

jsfiddle 演示http://jsfiddle.net/p8kkf/

希望对你有帮助

【讨论】:

  • :after 和 ::after 有区别吗?
  • ::after 更正确,但 :after 得到更好的支持,两者指的是同一个东西
【解决方案2】:

这是我用来旋转背景图像的旋转 css 类:

.rotating {
  -webkit-animation: rotating-function 1.25s linear infinite;
     -moz-animation: rotating-function 1.25s linear infinite;
      -ms-animation: rotating-function 1.25s linear infinite;
       -o-animation: rotating-function 1.25s linear infinite;
          animation: rotating-function 1.25s linear infinite;
}

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

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

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

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

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

【讨论】:

  • 感谢您的代码。我还没有尝试过尝试过,但是当所选的类被删除时,这也会将箭头从下降到右侧位置旋转? span>
  • 您必须在旋转后手动定位箭头。我喜欢@wes 建议使用:after 伪元素。