How to apply style to a class in javascript?

不想你离开。 提交于 2019-12-12 16:00:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!