34

是否可以为 CSS 伪类设置动画?

说我有:

#foo:after {
    content: '';
    width: 200px;
    height: 200px;
    background: red;
    display: block;
    -webkit-transition: all 1s ease-in-out;
    -moz-transition: all 1s ease-in-out;
    -o-transition: all 1s ease-in-out;
}

#foo:hover:after {
    width: 250px;
    height: 250px;
}

这甚至可能吗?我一直在测试,到目前为止我似乎无法找到解决方案。我试图通过使用 Modernizr 来减少我需要的 JavaScript 支持量。

我已经有一个 JavaScript 方法,所以请不要使用 JavaScript 替代方法。

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

4

4 回答 4

12

你的小提琴在 Firefox 中对我有用。据我所知,如果这篇文章是最新的,这是唯一可以为伪元素设置动画的浏览器。


编辑:截至 2016 年,文章的链接已损坏,相关的 WebKit 错误已在4 年前修复 。继续阅读以查看其他答案,这个已经过时了。

于 2011-10-18T15:54:10.577 回答
12

Google Chrome 将 webkit 错误修复添加到版本 27.0.1453.110 m

此 WebKit 错误已修复:http ://trac.webkit.org/changeset/138632

可以为伪:before元素和设置动画:after,这里有几个用于为伪元素设置动画的示例:before:after

这是对上面示例的修改,并进行了一些编辑,使其动画进出更加流畅,而没有悬停时的模拟mouseleave/mouseout延迟:

http://jsfiddle.net/MxTvw/234/

尝试在第二个伪类规则中添加#foo带有分组:hover伪类的主选择器。:hover还要添加transition属性,而不仅仅是供应商特定的前缀属性transition

#foo:after{
   display: block;
   content: '';
   width: 200px;
   height: 200px;
   background: red;
   -webkit-transition: all .4s ease-in-out;
   -moz-transition: all .4s ease-in-out;
   -o-transition: all .4s ease-in-out;
   transition: all .4s ease-in-out;
} 

#foo,
#foo:hover:after,
#foo:hover:before{
   width: 250px;
   height: 250px;
}

请注意,任何伪元素(如:beforeand ):after都应使用双冒号语法::before::after. 此示例使用叠加层background-colorbackground-image悬停来模拟淡入和淡出:

http://jsfiddle.net/MxTvw/233/

此示例模拟悬停时的旋转动画:

http://jsfiddle.net/Jm54S/28/

当然,我们可以使用 css3 标准,::before并且::after.

这适用于最新的 Firefox、Chrome、Safari、Opera 18+、IE10、IE11(IE9 及以下不支持 css3 过渡或动画。)

于 2012-10-20T03:50:55.273 回答
0

它现在似乎不起作用,但是根据W3 规范,您可以将转换应用于伪元素。也许在未来的某个时间......</p>

于 2011-10-18T15:51:34.990 回答
-3

我刚刚发现您可以为 :after 和 :before (:

代码示例-

  .model-item {
    position: relative;

    &:after {
      content: '';
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      right: 0;
      background: transparent;
      transition: all .3s;
    }
  }

  .opc {
    &:after {
      content: '';
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      right: 0;
      background: rgba(0, 51, 92, .75);
    }
  }

我有 div .model-item,我需要为他的 :after 设置动画。因此,我添加了另一个更改背景的类,并将转换代码添加到主:after(动画之前)

于 2017-01-30T13:34:42.147 回答