在 JavaScript 中,将 class 名称分配给常规元素和命名空间元素是否不同?
In JavaScript, Is assigning a class name to a regular element and a namespace element different?
function foo(){
var svg = document.querySelector(".crusher");
let polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.className = "polygon01";
svg.appendChild(polygon);
}
function foo01(){
let actualPolygon = document.querySelector(".polygon01");
actualPolygon.style = "fill:red";
}
当我尝试 select class 名称并更改填充颜色时,我收到无法访问空值样式,因此 class 名称不是以我希望的方式分配。任何帮助都会很棒。
尝试使用 setAttribute
function foo(){
var svg = document.querySelector(".crusher");
let polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.setAttribute('class', 'polygon01');
svg.appendChild(polygon);
}
function foo01(){
let actualPolygon = document.querySelector(".polygon01");
actualPolygon.style = "fill:red";
}
foo()
foo01();
查看您提供的 SVG 命名空间的 the spec,它说 className
已弃用并使用 classList
.
// create polygon and add class
let polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.classList.add("polygon01");
// append to element
document.querySelector(".crusher").appendChild(polygon);
// reference polygon with querySelector and add fill:red style
let actualPolygon = document.querySelector(".polygon01");
actualPolygon.style.fill = "red";
console.log(actualPolygon.style.fill);
<div class="crusher">
function foo(){
var svg = document.querySelector(".crusher");
let polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.className = "polygon01";
svg.appendChild(polygon);
}
function foo01(){
let actualPolygon = document.querySelector(".polygon01");
actualPolygon.style = "fill:red";
}
当我尝试 select class 名称并更改填充颜色时,我收到无法访问空值样式,因此 class 名称不是以我希望的方式分配。任何帮助都会很棒。
尝试使用 setAttribute
function foo(){
var svg = document.querySelector(".crusher");
let polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.setAttribute('class', 'polygon01');
svg.appendChild(polygon);
}
function foo01(){
let actualPolygon = document.querySelector(".polygon01");
actualPolygon.style = "fill:red";
}
foo()
foo01();
查看您提供的 SVG 命名空间的 the spec,它说 className
已弃用并使用 classList
.
// create polygon and add class
let polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.classList.add("polygon01");
// append to element
document.querySelector(".crusher").appendChild(polygon);
// reference polygon with querySelector and add fill:red style
let actualPolygon = document.querySelector(".polygon01");
actualPolygon.style.fill = "red";
console.log(actualPolygon.style.fill);
<div class="crusher">