下面的代码,用我自己写的方法getByclass同样可以取到包含16个元素的数组,但是不能得到属性值width,显示错误Cannot read property 'width' of undefined,如果把自己写的方法换成getElementsNameByTagName("div"),就可以取到宽度值50px,不懂为什么。麻烦大神帮看看,谢谢了~~
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title></title>
<style>
div,p,ul,li{margin:0;padding:0;}
li{list-style: none;}
a{text-decoration:none;}
div{position: relative;}
body{}
.redCube{width:50px;height: 50px;background: red;position: absolute;}
#s{width: 100px;height: 100px;background: blue;}
</style>
<script>
window.onload=function(){
var b = document.getElementById("s");
var str = "";
for(var i=0;i<16;i++){
str += "<div class='cube' style='width:50px;height: 50px;background: red;position: absolute;left:"+i*70+"px;' ></div>";
}
document.body.innerHTML=str;
var timer = null;
var num = 0;
var oCubes = getByClass(document,"cube");
alert(oCubes[0].style.width);
};
function getStyle(obj,attr){
return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj,null)[attr];
};
function getByClass(obj,Name){
var arr = [];
obj= obj?obj:document;
var aElement = obj.getElementsByTagName('*');
for(var i=0;i<aElement.length;i++){
if(aElement[i].className==Name){
arr.push(obj);
}
}
return arr;
};
</script>
</head>
<body>
</body>
</html>
这都不会
hello_world_mk
幕布斯0246692
相关分类