【问题标题】:How to access fill color property of an SVG, created with GSAP如何访问使用 GSAP 创建的 SVG 的填充颜色属性
【发布时间】:2021-12-22 20:55:40
【问题描述】:

HTML 代码:

<div class="dots" id="dotsSlider">
    <svg xmlns="http://www.w3.org/2000/svg" width="200" height="30" viewBox="0 0 400 60" id="ante">
    <rect width="100%" height="100%" fill="none" />
    </svg>
</div>

Javascript 代码:

for (let i = 0; i < 10; i++) {

    // targeting the svg itself
    const svgns = "http://www.w3.org/2000/svg";

    // variable for the namespace 
    var svg = document.querySelector("svg");

    var x = i.toString();
    var name = "newCircle" + x;
    var name2 = name;
    var counter = i + 1;
    var position = 36 * counter;

    // make a simple rectangle
    var name = document.createElementNS(svgns, "circle");

    // set attributes of new circle
    gsap.set(name, {attr: {
      cx: position, 
      cy: 25, 
      r: 8, 
      width: 30, 
      height: 30, 
      fill: "black",
      id: name2
    }});

    // append the new rectangle to the svg
    svg.appendChild(name);

}

到目前为止,我创建了 10 个 SVG(滑块的点)。 For 循环是在页面加载时运行的函数内部编写的。我的问题是我不知道如何访问这些 SVG 的填充属性,以便能够在另一个函数中以动态方式更改它。我尝试了与 getElement 将其解析为变量相关的所有操作,但可能我写错了。非常感谢任何帮助。

【问题讨论】:

标签: javascript object svg getelementbyid gsap


【解决方案1】:

试试这个:

var circle = document.getElementById("newCircle3");  // etc
circle.style.fill = "red";

【讨论】:

  • 不幸的是,我已经尝试过了。当我控制台记录它时它返回 null
  • 我只能使用 const element = document.getElementById("ante"); 访问 svg#ante 的 HTML 选择。 - 我的 svg 在 html 中的 id- 将它们显示为对象数组 - 在许多其他事物中 - 但我不知道如何继续
  • 好的。然后请用一个有效的例子来更新你的问题——最好是 StackOverflow sn-p——这样我们就可以自己看到了。
猜你喜欢
  • 2018-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多