如何使用js,添加子节点并且设置属性(class,id,onClick)进行定位。

意图:用最笨的方法,获得窗口的宽度高度,定义要追踪的精度(div的大小),得到个数,使用浮动属性,让其充满整个页面,利用坐标原理(宽,高),进行定位。求指正!!!
<html><head><title>定位测试</title><script type="text/javascript">var content=document.getElementById("content");var width = window.innerWidth;var height = window.innerHeight;var w = Math.round((width / 100));var h = Math.round((height / 100));for ( var i = 0; i < w; i++) {for ( var j = 0; j < h; j++) {var d = document.createElement("div");d.setAttribute("class", "square");d.setAttribute("id", i + "," + j);d.setAttribute("onClick", "select(" + i + "," + j + ")");content.appendChild(d);alert("-----");执行到这就出错了!!}}function select(w, h) {for ( var i = 0; i < width; i++) {for ( var j = 0; j < height; j++) {var s = document.getElementById(i + "," + j);if (i == w && j == h) {s.className = "";s.className += "square_over";alert(w + "x" + h);} else {s.className = "";}}}}</script><style type="text/css">body {margin: 0 auto;padding: 0;text-align: center;}div {magin: 0 auto;padding: 0;text-align: center;}.lac {margin: 0 auto;padding: 0;text-align: center;position: absolute;top: 0;bottom: 0;left: 0;right: 0;background: green;}.square {margin: 0 auto;padding: 0;width: 100px;height: 100px;background: blue;float: left;display: block;}.square_over {margin: 0 auto;padding: 0;width: 100px;height: 100px;background: red;float: left;display: block;}</style></head><body><div id="content"></div></body></html>

第1个回答  推荐于2018-05-10
太乱了,不想看,我估计你的意思就是说加节点,然后添加节点属性?
var elem=document.createElement('p');
elem.setAttribute("classname",'..')//for ie//class for ff!
elem.setAttribute('id','...');
得到要插入的元素,比如divx
document.getElementById('divx').appendChild(elem)
搞定了追问

和你的一样的,我也看了很多博客,基本原理是对的,但是我是说我的细节上有毛病,我的代码发的有些乱。谢了。

本回答被网友采纳
第2个回答  2014-01-07
把全部js代码放到</body>标签后吧,content变量为空,没有找到div为content的id本回答被提问者采纳
第3个回答  2014-01-07
d.setAttribute("onClick", "select(" + i + "," + j + ")")都写成"不支持啊亲
相似回答