关于点击div块关联到其他div块的显示与隐藏js
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>display</title>
<style>
#box{
width:500px;
height: 400px;
background:lightgoldenrodyellow;
border:1px solid black;
}
#head_list input{//div是块级元素,定义为float后在宽度允许的情况下,能在一行内容纳
float:left;
width:25%;
}
.active{//初始及点击后的按钮类
color: cornflowerblue;
}
</style>
</head>
<body>
<div id="head_list" style="height:250px;">
<div class="active" style="float:left;"><img src="ginovega-1.png"/></div>
<div style="float:left;"><img src="ginovega-1.png"/></div>
<div style="float:left;"><img src="ginovega-1.png"/></div>
<div style="float:left;"><img src="ginovega-1.png"/></div>
<!--<input type="button" value="菜单一" class="active" style="background:url(ginovega-1.png)"/>
<input type="button" value="菜单二" />
<input type="button" value="菜单三" />
<input type="button" value="菜单四" /> -->
</div>
<div id="menu_content" >
<div style="display:block;" class="div1"><div>test<div>55555</div></div>Hello,I am the first!</div>
<div style="display:none;" class="div1">Hello,I am the seconed!</div>
<div style="display:none;" class="div1"><div>test55<div>lalala</div></div>Hello,I am the third!</div>
<div style="display:none;" class="div1">Hello,I am the forth!</div>
</div>
<script type="text/javascript">
/*var head_list = document.getElementById("head_list");
var menu_content = document.getElementById("menu_content");
var oldiv = head_list.getElementsByTagName("div");//获取tab列表
var odiv = menu_content.getElementsByTagName("div");//获取tab内容列表
for(var i=0 ; i<oli.length ; i++){
oldiv[i].index = i;//定义index变量,以便让tab按钮和tab内容相互对应
oldiv[i].onclick = function( ){//移除全部tab样式和tab内容
for(var i =0; i < oli.length; i++){
oldiv[i].className = "";
odiv[i].style.display = "none";
}
this.className = "active";//为当前tab添加样式
odiv[this.index].style.display="block";//显示当前tab对应的内容
}
} */
window.onload = function() {
var click_divs = document.getElementById("head_list").getElementsByTagName("div");
var show_divs = document.getElementById("menu_content").getElementsByClassName("div1");
for(var i = 0; i < click_divs.length; i++) {
!function(a) {
// 点击 #click div
click_divs[a].onclick = function() {
// #show div 全部隐藏
for(var x = 0; x < show_divs.length; x++) {
show_divs[x].style.display = "none";
}
// 对应 #show div 显示
show_divs[a].style.display = "block";
// #click div 样式还原
for(var y = 0; y < show_divs.length; y++) {
click_divs[y].style.backgroundColor = '';
}
// 对应 #click div 样式设置背景色
click_divs[a].style.backgroundColor = '#dcf3fb';
};
}(i);
}
};
</script>
</body>
</html>
小结:获得网页中的对象的方法有
document.getElementById(“”);
document.getElementByTagName(“”);
document.getElementByClassName(“”);
js可以通过obj.style.属性名=“”;的方法来实现控制div的样式。