【问题标题】:How to change color of SVG element by clicking a button? [duplicate]如何通过单击按钮更改 SVG 元素的颜色? [复制]
【发布时间】:2017-02-08 20:54:22
【问题描述】:

我试过toggleClass,toggle,但这不起作用。 目标:有一个白色元素。我们单击一个按钮,元素变为例如蓝色。我们再次单击一个按钮,元素再次变为白色。 测试 3

【问题讨论】:

标签: jquery svg


【解决方案1】:

根据 jQuerys 发布说明,直到 3.0 版才支持 SVG 的类操作:https://blog.jquery.com/2015/07/13/jquery-3-0-and-jquery-compat-3-0-alpha-versions-released/

因此,如果您使用 jQuery 3.0(或更高版本)或者您自己使用 .attr() 方法操作类,它应该可以工作:

somejQueryElement.attr('class', 'new-value')

我在这里做了一个基本的例子:

http://jsfiddle.net/MattDiMu/q67h7bmf/

【讨论】:

    【解决方案2】:

    $(document).ready(function () {
        
            var flag = true; // take a flag here
        
            $(".S1").mouseover(function () {
                if (flag) { // check flag before change
                    $(".S1").css('fill', '158844');
                    $(".S1").css('stroke', '158844');
                }
            });
        
            $(".S1").mouseout(function () {
                if (flag) { // check flag before change
                    $(".S1").css('fill', '#000000');
                    $(".S1").css('stroke', '#000000');
                }
            });
        
            $(".S1").click(function () {
                flag = false; // reset flag
                $(".S1").css('fill', '158844');
                $(".S1").css('stroke', '158844');
            });
        
    });
    <svg>
    <line class = "S1" fill="none" stroke="#000000" stroke-width="3.8417" x1="73.208" y1="73.341" x2="99.923" y2="73.341"/>
    <polygon class = "S1" points="97.23,82.618 97.176,72.229 97.121,61.843 106.145,66.987 115.169,72.136 106.2,77.377 "/>
    </svg> 

    【讨论】:

      猜你喜欢
      • 2020-12-15
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-11
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多