Javascript 使用CreateElements创建的元素不显示
每次单击按钮时,我都试图用JavaScript创建一个新的标签。当我在控制台firebug中看到结果时,它工作正常,但屏幕上没有显示任何内容。 我想要的是,每次单击按钮时,都会在最后一个按钮之后显示一个图像 提前谢谢Javascript 使用CreateElements创建的元素不显示,javascript,svg,appendchild,Javascript,Svg,Appendchild,每次单击按钮时,我都试图用JavaScript创建一个新的标签。当我在控制台firebug中看到结果时,它工作正常,但屏幕上没有显示任何内容。 我想要的是,每次单击按钮时,都会在最后一个按钮之后显示一个图像 提前谢谢 var svgNS = "http://www.w3.org/2000/svg"; mybtn.addEventListener("click", createCircleSVG); function createCircleSVG(){ var
var svgNS = "http://www.w3.org/2000/svg";
mybtn.addEventListener("click", createCircleSVG);
function createCircleSVG(){
var d = document.createElement('svg');
d.setAttribute('id','mySVG');
document.getElementById("svgContainer").appendChild(d);
createCircle();
}
function createCircle(){
var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle."
myCircle.setAttributeNS(null,"id","mycircle" + opCounter++);
myCircle.setAttributeNS(null,"cx",25);
myCircle.setAttributeNS(null,"cy",25);
myCircle.setAttributeNS(null,"r",100);
myCircle.setAttributeNS(null,"fill","black");
myCircle.setAttributeNS(null,"stroke","blue");
document.getElementById("mySVG").appendChild(myCircle);
}
您需要使用CreateElements在svg名称空间中创建svg元素,就像您已经为圆圈所做的那样,例如
var d = document.createElementNS(svgNS, 'svg');
为SVG元素指定宽度和高度也是必要的
d.setAttribute("width", "100%");
d.setAttribute("height", "100%");
注意这里我们可以使用setAttribute,因为属性位于空名称空间中。如果需要,也可以转换circle setAttributeNS调用。创建SVG:
var svg = document.createElementNS(ns, 'svg');
第一个功能:
function createSVG() { ... }
function createSVGCircle() { createSVG() ... }
第二个功能:
function createSVG() { ... }
function createSVGCircle() { createSVG() ... }
或分开:
createSVG();
createSVGCircle();
相同答案的类似问题:您的svg正在插入,但超出了您的视口,因此您无法看到它,请为svg添加一些宽度和高度。。。