gpt4 book ai didi

javascript - 尝试访问 SVG 元素时 getElementById 返回 null

转载 作者:行者123 更新时间:2023-12-01 00:57:49 24 4
gpt4 key购买 nike

我正在尝试编写一个脚本来动态创建 SVG 元素并显示它。但是,当我设置 SVG 元素的 ID,然后尝试使用 Document.getElementById() 访问它时,它返回 null。我使用 window.onload 来确保在调用脚本之前文档已加载。

<body>
<script>
function buildSVG(color) {
const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
return shape;
}


function addSVG(color) {
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.id = "svgID";
let elem = document.getElementById("svgID");
elem.setAttribute('width', '600');
svg.setAttribute('height', '250');
svg.innerHTML = buildSVG(color);
svg.setAttribute('style', 'border: 1px solid black');
document.body.appendChild(svg);
}
window.onload = addSVG("cyan");
</script>
</body>

我希望显示一个青色方 block 。但是,我收到错误“无法读取 null 的属性 setAttribute”。

我可以做什么来解决这个问题?

最佳答案

当您创建 svg 元素时,您已经在分配的变量中引用了它。无需再次从文档中获取。这甚至是不可能的,因为它尚未添加到文档中。这是更正后的代码:

function buildSVG(color) {
const shape = `<rect x="0" y="0" width="90" height="90" stroke="black" fill="${color}"/>`;
return shape;
}


function addSVG(color) {
let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.id = "svgID";
svg.setAttribute('width', '600');
svg.setAttribute('height', '250');
svg.innerHTML = buildSVG(color);
svg.setAttribute('style', 'border: 1px solid black');
document.body.appendChild(svg);
}
window.onload = addSVG("cyan");

// after 1 second: get the svgID-element and change the border.
setTimeout(function(){
document.getElementById('svgID').setAttribute('style', 'border: 1px dashed red');
}, 1000);

关于javascript - 尝试访问 SVG 元素时 getElementById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56386573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com