如何使用 CSS 为按钮添加动画?


要在网页上为按钮添加动画,请使用 transition 属性。同时设置过渡动画的持续时间。使用按钮上的 :after 选择器,设置按钮在被点击之后外观如何发生改变的动画。

创建按钮

首先,使用 <button> 元素创建一个按钮 −

<button>Click Here</button>

设置按钮样式

此处的按钮具有样式。将位置设置为 relative,将光标设置为 pointer。此外,还设置宽度 −

button {
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   position: relative;
   background-color: rgb(100, 0, 84);
   border: none;
   font-size: 28px;
   color: rgb(255, 169, 255);
   padding: 20px;
   width: 200px;
   text-align: center;
   box-shadow: 5px 10px 18px rgb(121, 82, 185);
   text-decoration: none;
   overflow: hidden;
   cursor: pointer;
}

为被点击的按钮添加动画

transition 属性用于在按钮被点击之后立即设置动画。过渡动画的持续时间设置为 0.8 秒 −

button:after {
   content: "";
   background: rgb(251, 255, 0);
   display: block;
   position: absolute;
   padding-top: 300%;
   padding-left: 350%;
   margin-left: -20px;
   margin-top: -120%;
   opacity: 0;
   transition: all 0.8s
}

设置处于活动状态的按钮样式

:active 选择器用于在按钮处于活动状态时选择该按钮并设置其样式 −

button:active:after {
   padding: 0;
   margin: 0;
   opacity: 1;
   transition: 0s
}

示例

以下代码是使用 CSS 为按钮添加动画 −

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <style>
      button {
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         position: relative;
         background-color: rgb(100, 0, 84);
         border: none;
         font-size: 28px;
         color: rgb(255, 169, 255);
         padding: 20px;
         width: 200px;
         text-align: center;
         box-shadow: 5px 10px 18px rgb(121, 82, 185);
         text-decoration: none;
         overflow: hidden;
         cursor: pointer;
      }
      button:after {
         content: "";
         background: rgb(251, 255, 0);
         display: block;
         position: absolute;
         padding-top: 300%;
         padding-left: 350%;
         margin-left: -20px;
         margin-top: -120%;
         opacity: 0;
         transition: all 0.8s
      }
      button:active:after {
         padding: 0;
         margin: 0;
         opacity: 1;
         transition: 0s
      }
   </style>
</head>
<body>
   <h1>Animated Button Example</h1>
   <button>Click Here</button>
   <p>Click on the above button to see ripple effect</p>
</body>
</html>

更新于: 15-11-2023

226 次浏览

启动你的 职业生涯

完成课程即可获得认证

立即开始
广告
© . All rights reserved.