如何在JavaScript中将样式应用到类? [英] How to apply style to a class in javascript?

查看:118
本文介绍了如何在JavaScript中将样式应用到类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的身体有多个div,需要相同的风格:

I have multiple divs in my body which need the same style:

<div class="box"></div>

我有一个javascript来计算浏览器窗口视口高度的高度。
我想将这个高度应用到我的所有盒子分类的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>

这样做只有一个div,它不会使第二个boxdiv与上一个相同的高度。如果我将方括号中的数字从0更改为1,则将高度应用于第二个div。此外,如果我做一个javascript的第二个副本,使第一个脚本有[0],第二个[1]它应用的高度两个div。我不能删除方括号,因为那么javascript根本不工作。我也尝试用getElementsByTagName获取名称,但没有成功。

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.

如何使这个javascript适用于与box类的所有div相同的高度?

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?

推荐答案

请尝试以下操作:

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';
}

演示: http://jsfiddle.net/JRdHD/

这篇关于如何在JavaScript中将样式应用到类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆