【问题标题】:createElement() failing to work on basic path element [duplicate]createElement()无法处理基本路径元素[重复]
【发布时间】:2021-09-23 18:10:15
【问题描述】:

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

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
}
svg {
  transform: scale( 2 );
  border-radius: 0.25rem;
  width: 100px;
  height: 100px;
  background-color: rgba( 95%,95%,95%,0.5 );
  fill: #444;
}
<svg>
  <path 
    d=
      "
       M10 50
       C20 30, 40 30, 50 50
       C60 70, 80 70, 90 50
      "
   ></path>
</svg>

注意svgpath 元素以及d 属性的值。一切都在上面的 sn-p 中完美运行。

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

为什么path 元素不显示?

const svg = document.querySelector( `svg` ),
      path = document.createElement( `path` );

path.setAttribute(
  `d`,
  `
   M10 50
   C20 30, 40 30, 50 50
   C60 70, 80 70, 90 50  
  `
)

svg.appendChild( path );
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
}
svg {
  transform: scale( 2 );
  border-radius: 0.25rem;
  width: 100px;
  height: 100px;
  background-color: rgba( 95%,95%,95%,0.5 );
  fill: #444;
}
&lt;svg&gt;&lt;/svg&gt;

更令人困惑的是,我们可以看到浏览器似乎已经正确添加了该元素:

我们如何让path 元素正确出现在页面使用 JavaScript?

【问题讨论】:

    标签: javascript svg appendchild createelement


    【解决方案1】:

    createElementNS 与 SVG 命名空间 http://www.w3.org/2000/svg 一起使用:

    const svg = document.querySelector( `svg` ),
          path = document.createElementNS('http://www.w3.org/2000/svg', `path` );
    
    path.setAttribute(
      `d`,
      `
       M10 50
       C20 30, 40 30, 50 50
       C60 70, 80 70, 90 50  
      `
    )
    
    svg.appendChild( path );
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    html, body {
      height: 100%;
    }
    body {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    svg {
      transform: scale( 2 );
      border-radius: 0.25rem;
      width: 100px;
      height: 100px;
      background-color: rgba( 95%,95%,95%,0.5 );
      fill: #444;
    }
    &lt;svg&gt;&lt;/svg&gt;

    【讨论】:

    • 谢谢^^。这仅用于创建 SVG 元素吗?
    • 这用于描述 HTML 页面中的非 HTML 对象。 SVG 是其中之一,但还有其他的
    • 这似乎不适用于setAttributeNSstackoverflow.com/questions/68386339/…
    猜你喜欢
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 2021-09-18
    相关资源
    最近更新 更多