从Javascript插入时,SVG无法正常工作

时间:2019-01-28 11:35:45

标签: javascript svg

如果我在SVG中创建任何绘图,而不是将代码放入HTML文件中,而是从JS文件(带有... , link = "file:///C:\\Users\\...\\Desktop\\Eg_SomeExcelFile.xlsx" )插入,则svg及其所有笔划均以0x0大小呈现。 / p>

document.createElement('svg')
class Spinner {

  constructor(target) {

    this.target = document.getElementById(target);

    const spinner = document.createElement('svg');
    spinner.setAttribute('width', '100');
    spinner.setAttribute('height', '100');

    const spinnerPath = document.createElement('circle');
    spinnerPath.setAttribute('fill', 'red');
    spinnerPath.setAttribute('stroke', 'black');
    spinnerPath.setAttribute('stroke-width', '3');
    spinnerPath.setAttribute('cx', '50');
    spinnerPath.setAttribute('cy', '50');
    spinnerPath.setAttribute('r', '40');

    spinner.append(spinnerPath);

    this.target.append(spinner);

  }

}

new Spinner('here');

1 个答案:

答案 0 :(得分:1)

对于SVG元素,使用createElementNS代替createElement

const ns = 'http://www.w3.org/2000/svg';

class Spinner {
    constructor(target) {
        this.target = document.getElementById(target);

        const spinner = document.createElementNS(ns, 'svg');
        spinner.setAttribute('width', '100');
        spinner.setAttribute('height', '100');

        const spinnerPath = document.createElementNS(ns, 'circle');
        spinnerPath.setAttribute('fill', 'red');
        spinnerPath.setAttribute('stroke', 'black');
        spinnerPath.setAttribute('stroke-width', '3');
        spinnerPath.setAttribute('cx', '50');
        spinnerPath.setAttribute('cy', '50');
        spinnerPath.setAttribute('r', '40');

        spinner.appendChild(spinnerPath);

        this.target.appendChild(spinner);
    }
}

new Spinner('here');
<div id="here"></div>