微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 JavaScript 设置基本 SVG 元素的属性

如何解决使用 JavaScript 设置基本 SVG 元素的属性

首先,下面是没有添加任何 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 z" 
     />
  </circle>
</svg>

注意 animateMotion 元素和 path 属性的值。在上面的代码段中,一切都完美无缺。

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

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

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

animateMotion.setAttributeNS(
  `http://www.w3.org/2000/svg`,`path`,`M20,50 z`
);
* { Box-sizing: border-Box; margin: 0; padding: 0; }
html,50 z" 
  />

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

经过检查,我们可以看到浏览器似乎正确添加path 属性,正如它在第一个片段的 HTML 中显示的那样:

enter image description here

解决方法

尝试将 null 作为 const StyledDialog = withStyles({ root:{ backgroundColor:'transparent' // Outside of the Backdrop },paper:{ padding: 0,boxShadow:'none',height: 188,width:'35%',transition:' all 0.8s ease-in-out',borderRadius:14 } })(Dialog); // And add the class like this to the component you want to override <Component classes={{ root: classes.root,}} /> 中的 namespace 传递

setAttributeNS
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; }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。