如何在CSS中将所有动画设置为“无动画”?

时间:2017-07-29 18:00:07

标签: html css animation hover

我有一个网页,其中我正在尝试使用CSS动画制作菜单:

<html>
<body>
    <div class="orange-button">
    </div>
</body>
</html>

这是我链接的CSS文件:

.button-orange {
    border: none;
    transition: background 0.4s, border 0.4s, height 0.4s;
    background: orange;
}

.button-orange:hover {
    border-bottom: 3px solid blue;
    border-top: 3px solid rgba(0, 0, 0, 0);
    background: green;
    height: 94px;
}

div为100x100px,顶部边框仅用于保持文本在中间(否则上升1.5px)

我尝试使用大纲,但很快就放弃了它,因为它只能在所有方面使用。

当悬停时,一切正常,但当鼠标移动到其他地方时,bordes很快消失,高度也会动画。我怎样才能让他们同时进行动画制作?

1 个答案:

答案 0 :(得分:3)

border属性是一种速记,可以更改多个属性。通过应用border: none,您将border-stylesolid更改为none,无法转换(不可动画)。

要转换border-width,您需要在两个州都保留border-style:solid,并且只更改border-width

.button-orange {
    border: 0 solid;
    border-color: transparent transparent blue;
    transition: background 0.4s, border-width 0.4s, height 0.4s;
    background: orange;
}

.button-orange:hover {
    border-bottom: 3px solid blue;
    border-top: 3px solid rgba(0, 0, 0, 0);
    background: green;
    height: 94px;
}
 <div class="button-orange">Button</div>

但是,您会注意到转换border-width并不是很好看,主要是因为主流浏览器对边框的子像素值应用消除锯齿并且转换看起来不平滑。

对于“类边框”效果最常用和引人注目的效果是有一个额外的元素(通常是一个伪元素充当“实时”边框),从0动画到完整元素宽度,在X轴上。

例如:

.button-orange {
    transition: background-color 0.4s, height 0.4s;
    background: orange;
    position: relative;
    height: 18px;
}
.button-orange:hover {
    background-color: green;
    height: 94px;
}
.button-orange:after {
  content: '';
  height: 3px;
  width: 0;
  bottom: -3px;
  left: 50%;
  background-color: blue;
  position: absolute;
  transition: width .4s cubic-bezier(.4,0,.2,1);
  transform: translateX(-50%)
}

.button-orange:hover:after {
  width: 100%;
}
<div class="button-orange">Button</div>
(在改变宽度时不移动伪看起来更好 - 在我们的例子中,可能放在元素的顶部而不是底部)。

另一种可能的选择是保持相同的边框宽度并将边框设置为“实色”颜色到transparent,使border-width保持不变。由于border-width的差异,它看起来更平滑并使元素不会“跳跃”。

例如:

.button-orange {
    border: 3px solid transparent;
    transition: background 0.4s, border-color 0.4s, height 0.4s;
    background: orange;
    height: 18px;
}

.button-orange:hover {
    border-bottom-color: blue;
    background: green;
    height: 94px;
}
<div class="button-orange">Button</div>

另请注意,在您的初始示例(以及我的第一个代码段)中,height属性实际上不是动画,因为您尝试从默认设置动画,auto ,到一个特定的值,再次,是不可动画的。如果要为height设置动画,则需要在默认状态下设置值。它诱使你相信它的工作,但事实上,它是动画的border-width,创造了元素高度变化的错觉。事实上,边框正在改变width,而样式为none