<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title> 使用javascript通过className来获取元素 </title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> </head> <style> .red{ color: #F00; } #black{ color: #000; } </style> <body> <script type="text/javascript"> //获得id function $(id){ return document.getElementById(id); } //获得class 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 red_hidden(){ var redClassElements = getElementsByClassName('red'); for (var i=0; i<redClassElements.length; i++) { redClassElements[i].style.display = "none"; } } //显示艾它社区 function red_show(){ var redClassElements = getElementsByClassName('red'); for (var i=0; i<redClassElements.length; i++) { redClassElements[i].style.display = ""; } } </script> <a href="#" οnmοuseοver="red_hidden()" οnmοuseοut="red_show()">点我隐藏红色</a> <div class="red">艾它社区</div> <div class="red">艾它社区</div> <div class="red">艾它社区</div> <div>***************************************************************</div> <body> </html>
转载于:https://www.cnblogs.com/hongjiumu/archive/2012/09/12/2681278.html