【问题标题】:In JavaScript, Is assigning a class name to a regular element and a namespace element different?在 JavaScript 中,将类名分配给常规元素和命名空间元素是否不同?
【发布时间】:2020-10-01 18:37:57
【问题描述】:
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";
}

当我尝试选择类名并更改填充颜色时,我收到了无法访问空值样式,因此类名没有按照我希望的方式分配。任何帮助都会很棒。

【问题讨论】:

    标签: javascript namespaces classname


    【解决方案1】:

    尝试使用 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();

    【讨论】:

      【解决方案2】:

      查看您提供的 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">

      【讨论】:

      • 谢谢,是什么让您想到检查 SVG 的更新?只是想知道,这样我将来可以尝试自我纠正。
      • 在我们之间,这是我第一次查看规范,我之所以这样做只是因为 createElementNS(...).className 与我们预期的相比看起来很奇怪(一个空字符串,与 @987654328 相比@ 返回"")。多边形className 属性实际上吐出了一个看起来很奇怪的对象,看起来像SVGAnimatedString {baseVal: "", animVal: ""},我实际上并不知道那里发生了什么。这足以让我看看他们是否以某种方式破坏了className,果然,这个命名空间已被弃用。
      • 它看起来像是一个用于在动画期间动态更改类的界面或其他东西:developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedString。如果您好奇,请随意探索一下。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多