如何实现按钮悬停时的淡入淡出效果
在本指南中,您可以了解如何在使用鼠标悬停在按钮上时,在两种颜色之间实现平滑的淡入淡出效果。
在我们的按钮示例中,我们可以通过为 :hover 动态伪类定义不同的背景颜色来更改按钮的背景。然而,鼠标悬停在按钮上时,背景颜色会直接变为新颜色。为了在两者之间创建更平滑的过渡,我们可以使用 CSS Transitions(CSS 过渡)。
使用过渡
在添加了悬停状态所需的颜色后,将 transition 属性添加到按钮的规则中。对于简单的过渡,transition 的值是您希望此过渡应用的属性的名称,以及过渡应该花费的时间。
对于 :active 和 :focus 伪类,将 transition 属性设置为 none,这样按钮在点击时会直接变为活动状态。
在示例中,过渡需要 1 秒钟,您可以尝试更改此值,看看速度变化带来的不同效果。
html
<div class="wrapper">
<button class="fade">Hover over me</button>
</div>
css
.fade {
background-color: #db1f48;
color: white;
transition: background-color 1s;
}
.fade:hover {
background-color: #004369;
}
.fade:focus,
.fade:active {
background-color: black;
transition: none;
}
注意: transition 属性是 transition-delay、transition-duration、transition-property 和 transition-timing-function 的简写。请参阅 MDN 上这些属性的页面,以找到调整过渡的方法。