线条按钮动画

1 javascript css jquery svg

当悬停在按钮上时,我需要制作动画线,从顶线的中间开始,线应该朝不同的方向移动并改变颜色。关于应该像这样工作,但是,它从顶部中间开始:

代码笔

 <section class="hero">
      <div class="svg-container">
         <a class="magic-link" href="#">
            <svg class="gradient" height="60" width="320" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <linearGradient id="gradient">
                  <stop offset="0%" stop-color="#EB3349" />
                  <stop offset="95%" stop-color="#EB3349" />
                </linearGradient>
              </defs>
              <rect class="rect-shape" height="60" width="320" />
              <div class="text">Hover me</div>
            </svg>
         </a>
      </div>
    </section>
Run Code Online (Sandbox Code Playgroud)

Kre*_*dic 5

检查一下,现在这条线是顺时针方向的。

只需使用.rect-shape'sstroke-dasharraystroke-dashoffsetproperties 即可获得您最满意的效果:

 stroke-dasharray: 140 620;
 stroke-dashoffset: 274;
Run Code Online (Sandbox Code Playgroud)

当然你可以设置正或负的 dashoffset 值,然后你可以改变动画的方向

在官方页面上举一个更详细的例子:

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dashoffset

 stroke-dasharray: 140 620;
 stroke-dashoffset: 274;
Run Code Online (Sandbox Code Playgroud)
body {
  max-width: 100vh;
  margin: 0;
  color: #fff;
  font-size: 24px;
  background: #EB3349;
}

a, a:hover, a:focus, a:active, a:visited {
  color: #fff;
  text-decoration: none;
  font-size: 1em;
}

.hero {
  height: 100vh;
  width: 100vw;
}

.svg-container {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  margin: 0 auto;
  width: 320px;
  max-height: 60px;
  cursor: default;
}

.rect-shape {
  stroke-dasharray: 130 620;
  stroke-dashoffset: 274;
  stroke-width: 8px;
  fill: url(#gradient);
  /* modify this with the color you want */
  stroke: #fff;
  transition: stroke-width 1s, stroke-dashoffset 1s, stroke-dasharray 1s;
}

.text {
  font-family: serif;
  font-size: 22px;
  line-height: 32px;
  letter-spacing: 4px;
  color: #fff;
  top: -48px;
  position: relative;
  text-align: center;
}

.svg-container:hover .rect-shape {
  stroke-width: 2px;
  stroke-dashoffset: 0;
  stroke-dasharray: 760;
}

#gradient stop {
  transition: .5s all;
}

.svg-container:hover svg.gradient #gradient stop:first-child {
  stop-color: #EB3349;
}

.svg-container:hover svg.gradient #gradient stop:last-child {
  stop-color: #f45c43;
}
Run Code Online (Sandbox Code Playgroud)