问题
I have multiple divs in my body which need the same style:
<div class="box"></div>
I have a javascript that calculates the height of the browser window viewport height. I want to apply that height to all my "box" classed divs.
<script type="text/javascript">
var box = document.getElementsByClassName('box')[0];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
box.style.height=(height)+'px';
</script>
This works, but only with one div, it doesn't make the second "box" div the same height as the previous. If I change the number in square brackets from 0 to 1 it applies the height to the second div. Also, if I make a second copy of the javascript so that the first script has [0] and the second [1] it applies the height to both divs. I can't delete the square brackets because then the javascript doesn't work at all. I have also tried to get the name with getElementsByTagName with no success.
How can I make this javascript apply the same height to all the divs with "box" class? Or is there another way to do what I try to do?
回答1:
try the following:
var elems = document.getElementsByClassName('box'),
size = elems.length;
for (var i = 0; i < size; i++) {
var box = elems[i];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
box.style.height=(height)+'px';
}
Demo: http://jsfiddle.net/JRdHD/
回答2:
A simple way would be to document.write the style in the html, while the page is being read, after the link elements are defined.
<script>
document.writeln('<style>div.box{height:'+
document.documentElement.clientHeight+'px;}'+
'<\/style>');
</script>
</head>
<body...
来源:https://stackoverflow.com/questions/8688115/how-to-apply-style-to-a-class-in-javascript