如何使用浏览器的DOM在HTML和javascript中添加和随后的元素,包括属性?
下面是代码:如何使用浏览器的DOM在HTML和javascript中添加和随后的元素,包括属性?,javascript,html,dom,Javascript,Html,Dom,下面是代码: <!doctype html> <html> <head> <script type="text/javascript"> function stars() { var svg = document.createElement("svg"); var polygon = document.createElement("po
<!doctype html>
<html>
<head>
<script type="text/javascript">
function stars() {
var svg = document.createElement("svg");
var polygon = document.createElement("polygon");
polygon.setAttribute("style","width:70px;height:70px;")
// A star with the vector points.
polygon.setAttribute("points","10,1 4,19.8 19,7.8 1,7.8 16,19.8");
// More properties.
polygon.setAttribute("style","fill:yellow;stroke:yellow;stroke-width:1;fill-rule:nonzero;")
// Put in the parent element.
svg.appendChild(polygon);
// Then again, put this parent element in an existing element, that is: "div".
document.getElementById("littlediv").appendChild(svg);
}
</script>
<style type="text/css">
#littlediv
{
position:absolute;
width:100px;
height:100px;
}
svg
{
position:absolute;
height:100px;
width:100px;
}
polygon
{
position:absolute;
height:100px;
width:100px;
}
</style>
</head>
<body onload="stars()">
<div id="littlediv">
<!-- Here is where the created elements with it's attributes will append. -->
</div>
</body>
</html>
加载页面时,事件侦听器调用函数stars。然后在函数内部,创建html元素svg和随后的多边形,将多边形元素附加到svg,然后再次将svg元素附加到现有元素,即:div
现在,元素和附带的样式属性将整齐地插入到该元素的div标记中。但是,检查时,元素和属性声明不会显示在页面中。因此,在CSS中,我将所有元素的尺寸预设为100x100 px
当然,您可以复制/粘贴代码,使用.html后缀保存代码并进行检查
我做了什么蠢事吗?为什么元素不显示?更改:
var svg = document.createElement("svg");
var polygon = document.createElement("polygon");
致:
主要区别在于使用CreateElements而不是createElement
更多关于为什么 您好,您是否仍在尝试找到解决方案?
var xmlns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(xmlns, "svg");
var polygon = document.createElementNS(xmlns, "polygon");