如何使用 CSS 在悬停时添加过渡效果?


要使用 CSS 在悬停时添加过渡效果,首先,使用 :hover 选择器。在此之下,使用 transform 属性并缩放元素。对于过渡,使用 transition 属性。transition 简写属性允许我们在一行中将 transition-property、transition-duration、transition-timing-function 和 transition-delay 作为值指定给 transition 属性 -

  • transition-duration - 指定过渡效果完成所需的时间(秒或毫秒)

  • transition-property - 效果所作用的属性名称

  • transition-timing-function - 过渡的速度曲线

  • transition-delay - 以秒为单位设置过渡效果的延迟

请记住,您需要设置应用效果的 CSS 属性以及持续时间。

带持续时间的过渡

让我们来看一个在悬停时添加过渡效果的示例。我们使用 transition 简写属性设置了过渡持续时间 -

示例

Open Compiler
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; } .scaleBtn { display: inline-block; background-color: #0c1377; border: none; color: white; padding: 16px 32px; text-align: center; font-size: 16px; transition: 0.3s; margin: 20px; } .scaleBtn:hover { transform: scale(1.5); } </style> </head> <body> <h1>Transition on hover example</h1> <button class="scaleBtn">Hover Here</button> </body> </html>

带时间、持续时间、属性和延迟的过渡

在这个例子中,我们设置了所有属性的过渡 -

过渡持续时间

下面,为 border-radius 和 background-color 属性设置了持续时间。transition-duration 设置为 2 秒 -

2s for the border-radius property 2s for the background-color property

过渡延迟

延迟设置在 border-radius 和 background-color 属性上。transition-delay 分别设置为 1 秒和 2 秒;

1s for the border-radius property 2s for the background-color property

过渡时间函数

过渡设置在 border-radius 和 background-color 属性上。transition-timing-function 设置为 -

ease for the border-radius ease-out for the background-color property

示例

让我们来看一个设置带时间、持续时间、属性和延迟的过渡效果的示例。我们设置了 transition 简写属性 -

Open Compiler
<!DOCTYPE html> <html> <head> <style> .container div { width: 300px; height: 100px; border-radius: 1px; background-color: rgb(25, 0, 255); border: 2px solid red; transition: border-radius 2s ease 1s, background-color 2s ease-out 1s ; } .container:hover div { background-color: orange; border-radius: 50%; } </style> </head> <body> <h1>Transition shorthand property</h1> <div class="container"> <div></div> </div> <p>Hover over the above div to change its color and its shape to oval</hp> </body> </html>

更新于: 2023-11-15

532 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告