简体   繁体   中英

Can I make a transition on an SVG attribute that is not CSS?

I have an SVG that I would like to transition to extend when the mouse hovers over it, and ease back to its normal size when the mouse is not hovering. Because it is not adjusted through CSS, I can't figure out how to make that transition happen.

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

^ A link to an example of what I've got so far

Im new to javascript, any help is greatly appreciated, thank you.

I have already tried CSS transform scale and matrix, without working results.

<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>

As Robert Longson commented you can use SMIL animations: Inside the line #move there are 2 <animate> elements: the first for the mouseover and the second for mouseleave .

The first animation is changing the value of the x2 attribute of the line from="96.1" to="26" . The second element has no from attribute but is animating the value of the y2 to="96.1" The duration of both animations is dur="1s" and fill="freeze" is similar to the animation-fill-mode: forwards from CSS.

I hope it helps.

 .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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM