【问题标题】:How do i change svg attributes with js?如何用 js 更改 svg 属性?
【发布时间】:2022-01-03 11:30:56
【问题描述】:

今天我使用onclick方法在js中更改svg的属性时遇到了一些问题;

这是我想做的:

这就是我所做的:

有箭头,但灰色覆盖了它


这是我的代码:

function social() {
  document.getElementById("svg1").style.backgroundColor = "grey";
  document.getElementById("arrow").setAttribute("fill", "#ff00ff")
}
<div id="svg1">
  <svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13">
    <path fill="#6E8098"
    d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
  </svg>
</div>

【问题讨论】:

    标签: javascript html svg


    【解决方案1】:

    使用document.getElementById("arrow"),您正在搜索&lt;svg&gt; 元素。
    然后您将更改其fill 属性,但&lt;path /&gt; 元素的fill 属性会覆盖它。因此,您必须将 id="arrow"&lt;svg&gt; 移动到 pathfill&lt;path /&gt; 移动到 &lt;svg&gt;

    function social() {
      document.getElementById("svg1").style.backgroundColor = "grey";
      document.getElementById("arrow").setAttribute("fill", "#ff00ff")
    }
    <div id="svg1">
      <svg onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13">
        <path id="arrow" fill="#6E8098"
        d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
      </svg>
    </div>

    function social() {
      document.getElementById("svg1").style.backgroundColor = "grey";
      document.getElementById("arrow").setAttribute("fill", "#ff00ff")
    }
    <div id="svg1">
      <svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13" fill="#6E8098">
        <path 
        d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
      </svg>
    </div>

    【讨论】:

      【解决方案2】:

      我建议使用 CSS 类,然后使用 classlist.toggle 在点击时移动它:

      function social() {
        document.getElementById("arrow").classList.toggle('active');
      }
      .active {
          background: grey;
          border-radius: 30px;
          padding: 10px;
      }
      
      .active > path {
        fill: white;
      }
      <div id="svg1">
        <svg id="arrow" onclick="social()" xmlns="http://www.w3.org/2000/svg" width="15" height="13">
          <path id='path' fill="#6E8098"
          d="M15 6.495L8.766.014V3.88H7.441C3.33 3.88 0 7.039 0 10.936v2.049l.589-.612C2.59 10.294 5.422 9.11 8.39 9.11h.375v3.867L15 6.495z" />
        </svg>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-21
        • 2012-06-19
        • 1970-01-01
        • 2015-10-14
        • 2011-06-21
        • 2015-02-25
        • 1970-01-01
        • 2023-03-04
        相关资源
        最近更新 更多