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

您可以通过仅对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>

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

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

另请注意background-clip属性的使用。这会将背景颜色限制为仅内容区域(不包括边框(。

.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;
}
<div class="item"></div>

为了使动画正常工作,要设置动画的值必须具有定义的量,以便从和到进行动画处理。

由于您最初从未设置边框值,因此当鼠标离开元素时,动画没有任何动画效果。

解决此问题的方法是将初始边框设置为border:0 solid green;。然后,悬停动画将在悬停时从 0 平滑地从 0 到 8px 进行动画处理,并在鼠标离开时平滑地回落到 0。

这里的例子

您可以最初向div 添加透明边框。然后对颜色进行动画处理。为了保持div的宽度和高度,添加box-sizing: border-box...

.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;
}
<div class="item"></div>

发生这种情况是正常的,因为您没有添加边框。边框仅具有悬停效果。因此,当您将鼠标指针取出浏览器时,浏览器不知道是否有边框。因此,您必须添加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;
}

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

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

最新更新