【问题标题】:Set attribute of basic SVG element with JavaScript使用 JavaScript 设置基本 SVG 元素的属性
【发布时间】:2021-07-15 00:01:39
【问题描述】:

首先,下面是没有添加任何 JavaScript 的预期结果

* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body { display: flex; justify-content: center; align-items: center; }
svg { width: 12.5rem; height: 6rem; }
path { fill: none; stroke: #444; stroke-width: 5px; }
circle { opacity: 0.75; fill: #0dd; }
<svg>
  <path
    d="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" 
  />

  <circle r='10'>
    <animateMotion 
      dur="5s" repeatCount="indefinite"
      path="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" 
     />
  </circle>
</svg>

注意animateMotion 元素和path 属性的值。一切都在上面的 sn-p 中完美运行。

然而,在下面的 sn-p 中,我们还没有在 animateMotion 元素上添加 path 属性,因此我们尝试使用 JavaScript 插入它。在完成的程序中,path 属性将填充动态值。

当 DOM 结构相同时,为什么 animateMotion 元素在这里不像在第一个 sn-p 中那样工作?

let animateMotion = document.querySelector( `animateMotion` );

animateMotion.setAttributeNS(
  `http://www.w3.org/2000/svg`, `path`, 
  `M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z`
);
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body { display: flex; justify-content: center; align-items: center; }
svg { width: 12.5rem; height: 6rem; }
path { fill: none; stroke: #444; stroke-width: 5px; }
circle { opacity: 0.75; fill: #0dd; }
<svg>
  <path
    d="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" 
  />

  <circle r='10'>
    <animateMotion 
      dur="5s" repeatCount="indefinite"
     />
  </circle>
</svg>

经过检查,我们可以看到浏览器似乎已经正确添加了 path 属性,与它在第一个 sn-p 的 HTML 中出现的完全一样:

【问题讨论】:

  • 使用 setAttribute,而不是 setAttributeNS。只有元素在 SVG 命名空间中,属性不在。

标签: javascript html svg setattribute svg-animationelements


【解决方案1】:

尝试在setAttributeNS 中将null 作为namespace 传递

let animateMotion = document.querySelector( `animateMotion` );

animateMotion.setAttributeNS(
  null, `path`, 
  `M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z`
);
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body { display: flex; justify-content: center; align-items: center; }
svg { width: 12.5rem; height: 6rem; }
path { fill: none; stroke: #444; stroke-width: 5px; }
circle { opacity: 0.75; fill: #0dd; }
<svg>
  <path
    d="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" 
  />

  <circle r='10'>
    <animateMotion 
      dur="5s" repeatCount="indefinite"
     />
  </circle>
</svg>

【讨论】:

  • 如果你使用 setAttribute 更容易,那么你可以省略最初的 null。
猜你喜欢
  • 2014-02-07
  • 1970-01-01
  • 2015-01-28
  • 2021-05-16
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 2010-09-25
相关资源
最近更新 更多