用于在SVG中创建具有外来对象的textarea的Javascript无法正常工作

时间:2015-03-27 07:22:31

标签: javascript html svg

拥有以下html / javascript:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<svg id = "svg" xmlns="http://www.w3.org/2000/svg" width = "800" height = "400"  >
  <foreignobject id = "x" x = "50" y = "50" width = "300" height = "100">
  <textarea rows = "3" cols = "30" border = "1px"> hello </textarea>
</foreignobject>  
</svg>
<script>
var fo = document.createElementNS("http://www.w3.org/2000/svg", "foreignobject");
fo.setAttribute("id", "y");
fo.setAttribute("x", "200");
fo.setAttribute("y", "300");
fo.setAttribute("width", "300");
fo.setAttribute("height", "100");
var ta = document.createElement("textarea");
ta.rows = 3;
ta.cols = 30;
ta.innerHTML = "world";
fo.appendChild(ta);
document.getElementById("svg").appendChild(fo);
</script>
</body>
</html>

svg中的异物内部有一个文本区域,它按预期显示。但是,我也有尝试创建完全相同的java脚本,但文本区域不会出现。在Chrome浏览器上试过这个。我做错了什么?

3 个答案:

答案 0 :(得分:1)

SVG元素名称区分大小写。请尝试使用foreignObject代替foreignobject

答案 1 :(得分:1)

这只是因为您错过了XHTML命名空间而foreignObject而不是foreignobjecthttp://jsfiddle.net/49sg5j5m/4/

var ta = document.createElementNS("http://www.w3.org/1999/xhtml", "textarea");

答案 2 :(得分:0)

使用此代码

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <svg id = "svg" xmlns="http://www.w3.org/2000/svg" width = "800" height = "400"  >
        <foreignObject id = "x" x = "50" y = "50" width = "300" height = "100">
            <textarea rows = "3" cols = "30" border = "1px"> hello </textarea>
        </foreignObject>  
    </svg>

<script>
var fo = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
fo.setAttribute("id", "y");
fo.setAttribute("x", "200");
fo.setAttribute("y", "300");
fo.setAttribute("width", "300");
fo.setAttribute("height", "100");
var ta = document.createElement("textarea");
ta.rows = 3;
ta.cols = 30;
ta.innerHTML = "world";
fo.appendChild(ta);
document.getElementById("svg").appendChild(fo);
</script>
</body>
</html>