日期:2014-05-17  浏览次数:20588 次

Javascript获取相同CSS样式的元素
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
.red {
	background-color: #F00;
	height: 100px;
	width: 100px;
}

.green {
	background-color: #0F0;
	height: 100px;
	width: 100px;
}
</style>
</head>
<script language="javascript">
	function getElementsByClassName(n) {
		var classElements = [], allElements = document
				.getElementsByTagName('*');
		for ( var i = 0; i < allElements.length; i++) {
			if (allElements[i].className == n) {
				classElements[classElements.length] = allElements[i];
			}

		}
		return classElements;
	}
	function changeBlue() {
		var redClassElements = [];
		redClassElements = getElementsByClassName('red');
		for ( var i = 0; i < redClassElements.length; i++) {
			redClassElements[i].className = "green";
			alert(i);
		}
	}
</script>
<body>
	<div class="red" onclick="changeBlue()"></div>
	<br />
	<div class="red"></div>
</body>
</html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title>无标题文档</title>
<style type="text/css">
.red {
	height: 100px;
	width: 100px;
	background-color: #F00;
}
</style>
</head>
<script language="javascript" src="jquery-1.2.6.min.js"></script>
<script language="javascript">
	function changeColor() {
		$(".red").css("background-color", "#0F0");
	}
</script>
<body onclick="changeColor()">
	<div class="red"></div>
	<br />
	<div class="red"></div>
	<br />
	<div class="red"></div>
</body>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
.red {
	height: 100px;
	width: 100px;
	background-color: #F00;
}

.green {
	height: 100px;
	width: 100px;
	background-color: #0F0;
	display: none;
}
</style>
</head>
<script language="javascript" src="jquery-1.2.6.min.js"></script>
<script language="javascript">
	function changeTheRedColor() {
		$(".red").css("background-color", "#00F");
	}
	function showGreenDiv(objId) {
		var str = "#" + objId
		alert(str);
		$(str).css("display", "block");
	}
</script>
<body onclick="changeTheRedColor()">
	<div class="red" onclick="showGreenDiv('1g')"></div>
	<br />
	<div class="red" onclick="showGreenDiv('2g')"></div>
	<br />
	<div class="red" onclick="showGreenDiv('3g')"></div>
	<br />
	<div class="green" id="1g"></div>
	<br />
	<div class="green" id="2g"></div>
	<br />
	<div class="green" id="3g"></div>
</body>