oParent.style.cssText = 'width:' + oBoxW*cols +'px;margin:0 auto';在浏览器里没有效果,console.log()也没有输出内容,有人知道这是怎么回事吗?
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>2.1HTML CSS实现瀑布流布局页面</title> <link rel="stylesheet" type="text/css" href="css/style.css"> <script type="text/javascript"> window.load = function(){ waterfall("main","box"); }; function waterfall(parent,box){ //将main下所有class为box的元素取出来 var oParent = document.getElementById(parent); var oBoxs = getByClass(oParent,box); // console.log(oBoxs.length); // 计算整个页面显示的列数(页面宽/box的宽) var oBoxW = oBoxs[0].offsetWidth; // console.log(oBoxW); var cols = Math.floor(document.documentElement.clientWidth/oBoxW); //console.log(cols); //设置mian的宽度 oParent.style.cssText = 'width:' + oBoxW*cols +'px;margin:0 auto'; } //根据class获取元素 function getByClass(parent,clsName){ var boxArr = new Array();//用来存储获取到的所有class为box的元素 var oElements = parent.getElementsByTagName('*'); for (var i = 0; i < oElements.length; i++) { if(oElements[i].className == clsName){ boxArr.push(oElements[i]); } } return boxArr; } </script> </head> <body> <div id="main"> <div> <div> <img src="images/P_00.jpg"> </div> </div> <div> <div> <img src="images/P_01.jpg"> </div> </div> <div> <div> <img src="images/P_02.jpg"> </div> </div> <div> <div> <img src="images/P_03.jpg"> </div> </div> <div> <div> <img src="images/P_04.jpg"> </div> </div> <div> <div> <img src="images/P_05.jpg"> </div> </div> <div> <div> <img src="images/P_06.jpg"> </div> </div> <div> <div> <img src="images/P_07.jpg"> </div> </div> <div> <div> <img src="images/P_08.jpg"> </div> </div> <div> <div> <img src="images/P_09.jpg"> </div> </div> <div> <div> <img src="images/P_010.jpg"> </div> </div> <div> <div> <img src="images/P_011.jpg"> </div> </div> <div> <div> <img src="images/P_012.jpg"> </div> </div> <div> <div> <img src="images/P_013.jpg"> </div> </div> <div> <div> <img src="images/P_014.jpg"> </div> </div> <div> <div> <img src="images/P_015.jpg"> </div> </div> <div> <div> <img src="images/P_016.jpg"> </div> </div> <div> <div> <img src="images/P_017.jpg"> </div> </div> <div> <div> <img src="images/P_018.jpg"> </div> </div> <div> <div> <img src="images/P_019.jpg"> </div> </div> </div> </body> </html>
我跟着老师写的代码里,不会出现固定宽度,即oParent.style.cssText = 'width:' + oBoxW*cols +'px;margin:0 auto';在浏览器里没有效果,另,在控制台上,console.log()也没有输出内容,有哪位知道这是怎么回事吗?