【发布时间】: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>
注意svg 和path 元素以及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;
}
<svg></svg>
更令人困惑的是,我们可以看到浏览器似乎已经正确添加了该元素:
我们如何让path 元素正确出现在页面使用 JavaScript?
【问题讨论】:
标签: javascript svg appendchild createelement