简体   繁体   English

使用JavaScript在SVG元素上动画填充不透明度

[英]Animating fill-opacity on SVG element using JavaScript

I have an SVG object which consists of multiple paths. 我有一个由多个路径组成的SVG对象。 For each of these paths, a JavaScript function is attached to the "onmouseout" event. 对于这些路径中的每一个,JavaScript函数都将附加到“ onmouseout”事件。 This is shown below: 如下所示:

<path id="AUK" style="fill:#00A600;" onmouseover="m_over(this.id);" onmouseout="m_out(this.id);" d="M142.3397,326l-8.66,-15l8.66,-15h17.32l8.66,15l-8.66,15H142.3397z"/>

When the user hovers their mouse over this element, the opacity is set to 0.3 (function not shown). 当用户将鼠标悬停在此元素上时,不透明度设置为0.3(功能未显示)。 When the user's mouse leaves this element, the opacity is reset to 1.0. 当用户的鼠标离开该元素时,不透明度将重置为1.0。 The function that achieves this is shown below: 实现此功能的功能如下所示:

function m_out(hover_id) { 
document.getElementById(hover_id).setAttribute("fill-opacity", "1.0"); }

I want to fade (or animate ) the opacity from 0.3 to 1.0 over 1 second. 我想在1秒钟内将不透明度从0.3淡化(或设置动画)。 Currently this transition occurs (almost) instantly. 当前,此转换(几乎)立即发生。

Ideally, I would like to achieve this using code similar to whats listed above. 理想情况下,我想使用类似于上面所列代码的代码来实现此目的。

Where should I start...? 我应该从哪里开始...?

You can add css transitions to your stylesheet 您可以将CSS过渡添加到样式表中

#AUK{
    -webkit-transition: fill-opacity 1s;
    transition: fill-opacity 1s;
}

with this you could even make this in pure css. 有了它,您甚至可以在纯CSS中做到这一点。

 <style> circle { -webkit-transition: fill-opacity 1s; /* Safari */ transition: fill-opacity 1s; } circle:hover {fill-opacity:0.1} </style> <svg> <circle cx="50" cy="50" r="45" fill="blue" stroke="darkblue" stroke-width="8"/> </svg> 

If you want the transtion to work only one way (ie only on mouseout on mouseover) you can use a class selector and add or remove the class as needed. 如果您希望转换仅以一种方式工作(即,仅在鼠标悬停时在鼠标移开时),则可以使用类选择器并根据需要添加或删除类。

 function m_over(evt){ evt.target.setAttribute("fill-opacity","0.2") evt.target.removeAttribute("class") } function m_out(evt){ evt.target.setAttribute("fill-opacity","1") evt.target.setAttribute("class","fade") } 
 <style> .fade { -webkit-transition: fill-opacity 1s; /* Safari */ transition: fill-opacity 1s; } </style> <svg> <circle cx="50" cy="50" r="45" fill="blue" stroke="darkblue" stroke-width="8" onmouseover="m_over(evt)" onmouseout="m_out(evt)"/> </svg> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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