CSS实现按钮边框动画效果

首先说下大概的实现思路:按钮元素的边框是无法设置动画效果的(其他元素也一样),所以要实现边框的动画效果,首先要在元素内添加四个空元素来模拟元素的四个边框(通常是空内容的span标签)。下面是一些大致的实现思路:

  • 首先给按钮设置 position: relative,然后给 span 标签设置 position: absolue ,通过 CSS 分别将四个 span 标签定位到元素的四周,模拟成了四条边
  • 对于上下边框,可以设置动画效果,如果是上边框,则在 x 轴上设置过渡效果,从-100% 到 100%,如果是下边框则从 100% 到 -100%(这里不是 0,如果是 0 的话,如果为 0 的话,当线条从右往左运动时,线的左断点一到元素的左边框位置就结束了)
  • 对于左右边框,与上下边框的实现思路相似,只是在 y 轴上进行过渡。

代码:

<button>
   Button
   <span>span>
   <span>span>
   <span>span>
   <span>span>
 button>
button {
  position: relative;
  margin: 10rem 0 0 10rem;
  border: none;
  font-size: 4rem;
  padding: 1rem 2rem;
  background-image: linear-gradient(135deg, #abdcff 10%, #0396ff 100%);
  color: white;
  outline: none;
  letter-spacing: 0.4rem;
  box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.5);
  overflow: hidden;
}

/* 上边框 */
button span:nth-child(1) {
  position: absolute;
  top: 0;
  left: 0;
  height: 0.2rem;
  width: 100%;
  background-image: linear-gradient(to left, #43cbff, #9708cc);
  animation: line1 1s linear infinite;
}

@keyframes line1 {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}

/* 右边框 */
button span:nth-child(2) {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 0.2rem;
  background-image: linear-gradient(to bottom, #43cbff, #9708cc);
  animation: line2 1s linear infinite;
  animation-delay: 1.5s;
}

@keyframes line2 {
  0% {
    transform: translateY(-100%);
  }
  100% {
    transform: translateY(100%);
  }
}

/* 下边框 */
button span:nth-child(3) {
  position: absolute;
  bottom: 0;
  right: 0;
  height: 0.2rem;
  width: 100%;
  background-image: linear-gradient(to right, #43cbff, #9708cc);
  animation: line3 1s linear infinite;
}

@keyframes line3 {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}

/* 左边框 */
button span:nth-child(4) {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 100%;
  width: 0.2rem;
  background-image: linear-gradient(to top, #43cbff, #9708cc);
  animation: line4 1s linear infinite;
  animation-delay: 1.5s;
}

@keyframes line4 {
  0% {
    transform: translateY(100%);
  }
  100% {
    transform: translateY(-100%);
  }
}

实现效果:

CSS实现按钮边框动画效果

你可能感兴趣的:(css,css3,html)