【问题标题】:Can I make a transition on an SVG attribute that is not CSS?我可以对非 CSS 的 SVG 属性进行转换吗?
【发布时间】:2020-02-27 22:15:09
【问题描述】:

我有一个 SVG,我想在鼠标悬停在它上面时过渡到扩展,并在鼠标不悬停时恢复到正常大小。因为它不是通过 CSS 调整的,所以我不知道如何实现这种转换。

https://codepen.io/BrendanOB/pen/LYYepQQ

^ 一个指向我目前所获得的示例的链接

我是 javascript 新手,非常感谢任何帮助,谢谢。

我已经尝试过 CSS 变换比例和矩阵,但没有工作结果。

<style>
 .st2{fill:#E5CACA;}
 .st3{fill:none;stroke:#FFF;stroke-width:17;stroke-linecap:round;stroke-miterlimit:10;}
</style>

<g id="Layer_2">
   <line class="st3" x1="500" y1="142" x2="500" y2="95"/>
   <line onmouseover="bigLine()" onmouseleave="smallLine()" id="move" class="st3" x1="518.2" y1="142.9" x2="521.8" y2="96.1"/>
   <line id="stretch" class="st3" x1="536" y1="144.7" x2="544" y2="98.3"/>
</g>

<script>
 function bigLine(){
     var lines = document.querySelector('#Layer_2')
     var l = lines.querySelector('#move')
     console.log(l);
     l.transition = "all 2s";
     l.setAttribute("y2", "26");
   }

   function smallLine(){
     var lines = document.querySelector('#Layer_2')
     var l = lines.querySelector('#move')
     console.log(l);
     l.transition = "all 2s";
     l.setAttribute("y2", "96");
   }
</script>

【问题讨论】:

  • CSS 动画仅适用于 CSS 属性。你可以在这里使用 SMIL。
  • 您可以在内联 svg 上使用 css 动画。我认为你需要改变动画的方式。也许尝试一下stroke dasharray和stroke dashoffset。您也可以使用 css js 或 smil css-tricks.com/svg-line-animation-works 制作动画

标签: javascript animation svg transition


【解决方案1】:

正如 Robert Longson 所说,您可以使用 SMIL 动画:#move 行内有 2 个 &lt;animate&gt; 元素:第一个用于 mouseover,第二个用于 mouseleave。

第一个动画是改变from="96.1" to="26" 行的x2 属性值。第二个元素没有from 属性,但是动画y2 的值​​to="96.1" 两个动画的持续时间是dur="1s" 和fill="freeze" 类似于CSS 中的animation-fill-mode: forwards。

希望对你有帮助。

.st2 {
  fill: #e5caca;
}
.st3 {
  fill: none;
  stroke: #ddd;
  stroke-width: 17;
  stroke-linecap: round;
  stroke-miterlimit: 10;
  
}
<svg viewBox="0 0 1000 1000" style="enable-background:new 0 0 1000 1000;">
  <g id="Layer_2">
	<line class="st3" x1="500" y1="142" x2="500" y2="95"/>
    <line id="move" class="st3" x1="518.2" y1="142.9" x2="521.8" y2="96.1">
       <animate
    	attributeType="XML" 
        attributeName="y2" 
        from="96.1" to="26" 
        begin="mouseover"
        dur="1s" 
        fill="freeze" />
       <animate
    	attributeType="XML" 
        attributeName="y2" 
        to="96.1" 
        begin="mouseleave"
        dur="1s" 
        fill="freeze" />
    </line>
	<line id="stretch" class="st3" x1="536" y1="144.7" x2="544" y2="98.3"/>
</g> 
</svg>

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2021-08-29
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多