CSS动画边框进出

时间:2017-07-18 13:33:46

标签: html css

我正在使用以下css来设置悬停边框的动画:

.item {
  height: 250px;
  width: 250px;
  display: block;
  background: orange; 
  -webkit-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}

.item:hover {
  border: 8px solid green;
}

它适用于悬停,但是当我将鼠标移出时,边框会在没有动画的情况下消失。是否也可以滑出边框?

https://codepen.io/anon/pen/rwgZXp

6 个答案:

答案 0 :(得分:5)

您可以通过仅设置动画border-width

来解决此问题

查看结果:

.item {
  height: 250px;
  width: 250px;
  display: block;
  background: orange;
  -webkit-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
  border: 0px solid green;
}

.item:hover {
  border-width: 8px;
}
<div class="item"></div>

答案 1 :(得分:3)

.item上添加透明边框,并在悬停时更改颜色。

.item {
  border: 8px solid transparent;
  background-clip: content-box;
}
.item:hover {
  border-color: green;
}

另请注意background-clip属性的使用。这会将背景颜色仅限制在除边框之外的内容区域。

&#13;
&#13;
.item {
  height: 250px;
  width: 250px;
  display: block;
  background: orange; 
  border: 8px solid transparent;
  background-clip: content-box;
  -webkit-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}

.item:hover {
  border-color: green;
}
&#13;
<div class="item"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:3)

为了使动画有效,您动画的值必须具有定义的动画来源和来源。

由于您从未初步设置边框值,因此当鼠标离开元素时,动画无法动画回原点。

解决此问题的方法是将初始边框设置为border:0 solid green;。然后悬停动画将在悬停时平滑地从0到8px动画,并在mouseleave上平滑地回到0。

Example here

答案 3 :(得分:0)

您最初可以为div添加透明边框。然后为颜色设置动画。为了保留div的宽度和高度,添加box-sizing: border-box ...

&#13;
&#13;
.item {
  height: 250px;
  width: 250px;
  display: block;
  background: orange;
  box-sizing: border-box;
  border: 8px solid transparent;
  -webkit-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}

.item:hover {
  border: 8px solid green;
}
&#13;
<div class="item"></div>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您可以轻松为border: 0px solid green;添加.item

答案 5 :(得分:0)

这是正常的,因为您还没有添加边框。边界只有悬停效果。所以当你把鼠标指针拿出来时,浏览器并不知道是否有边框。所以你必须添加一个0px大小的边框,如下所述。

.item {
  height: 250px;
  width: 250px;
  display: block;
  border: 0px solid green;
  background: orange; 
  -webkit-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}

.item:hover {
  border: 8px solid green;
}

我希望这会给你你想要的东西。