【问题标题】:How to change svg path width on hover如何在悬停时更改 svg 路径宽度
【发布时间】:2021-05-10 23:18:12
【问题描述】:

我有一个问题,我找不到有用的答案。我有一个 svg 箭头,当用户用鼠标悬停时箭头必须增长。问题是只有线必须改变大小而不是箭头。我只是想让这条线水平增长。 这是svg代码

<svg width="51" height="8" viewBox="0 0 51 8" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M50.3536 4.35355C50.5488 4.15829 50.5488 3.84171 50.3536 3.64645L47.1716 0.464466C46.9763 0.269204 46.6597 0.269204 46.4645 0.464466C46.2692 0.659728 46.2692 0.976311 46.4645 1.17157L49.2929 4L46.4645 6.82843C46.2692 7.02369 46.2692 7.34027 46.4645 7.53553C46.6597 7.7308 46.9763 7.7308 47.1716 7.53553L50.3536 4.35355ZM0 4.5H50V3.5H0V4.5Z" fill="black"/>
</svg>

这是我现在正在工作的代码

svg {
    width: 50px;
    overflow: visible;
    transition: width 0.5s ease;
}

svg:hover {
    width: 100px;
}

我还有一个 Codepen 链接 https://codepen.io/godhandkiller/pen/xxRZeYv

这里的问题是我正在操作整个 SVG,但我只需要更改类似的大小。

【问题讨论】:

  • 你不能。路径包括箭头,因此不能单独影响。您需要第二条路径只是箭头来做到这一点。
  • 您的 SVG 路径不是笔画。 SVG stroke-width PropertyExample

标签: css svg path


【解决方案1】:

一个可能的解决方案:您可以使用带有标记端的线路路径。标记是箭头的尖端。对于动画,我使用 SMIL 动画将路径的 d 属性从 M1,4L25,4 更改为 M1,4L50,4。 animate 元素有一个 begin 属性,当您将鼠标悬停在覆盖的矩形上时,动画就会开始:begin="theRect.mouseover"。另一个动画元素在鼠标移出时为路径设置动画:begin="theRect.mouseout"

svg {
  border: 1px solid red;
  transition: width 0.5s ease;
}
<svg id="theSVG" fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 51 8" stroke="#000" stroke-linecap="round">
  <defs>
    <marker id="m" overflow="visible" markerUnits="userSpaceOnUse">
      <path d="M-3,-3L0,0 -3,3" />
    </marker>

  </defs>

  <path d="M1,4L25,4" marker-end="url(#m)">
    <animate attributeName="d" to="M1,4L50,4" dur="1s" begin="theRect.mouseover" repeatCount="1" fill="freeze" />
    <animate attributeName="d" to="M1,4L25,4" dur="1s" begin="theRect.mouseout" repeatCount="1" fill="freeze" />
  </path>

  <rect width="100%" height="100%" stroke="none" pointer-events="all" id="theRect" />
</svg>

【讨论】:

  • 这正是我需要的,我只需要玩弄这些值。我注意到“悬停”动作在 svg 内,有没有办法改变它,所以它是父 div?问题是由于箭头太小,很难触发动画
  • 当您将鼠标悬停在覆盖的透明矩形上时会触发动画。这个矩形覆盖了所有的 svg 元素。另外:由于 svg 元素有一个 viewBox 属性并且没有宽度,因此采用了覆盖所有父元素的整个可用宽度
猜你喜欢
  • 2021-03-05
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 2021-12-24
相关资源
最近更新 更多