最近在学习JavaScript的过程中,做了一些小Demo,想在博客上记录一下。
这是一个选项卡的例子,就是点击不同的按钮,显示不同的内容。
思路是先隐藏所有内容,在根据点击的按钮显示出相应的内容。代码如下:
<html>
<head>
<title>选项卡</title>
<style>
.active{
background: orange;
}
#div1 div{
width:200px;
height:200px;
background: lavenderblush;
border: 1px solid black;
display: none;
}
</style>
<script>
window.onload=function(){
var input = document.getElementsByTagName("input");
var div1 = document.getElementById("div1");
var div = div1.getElementsByTagName("div");
for(var i = 0;i < input.length;i++){
input[i].index = i;
input[i].onclick = function(){
//这个for循环就是让所有的样式先清空
for(var i=0;i<input.length;i++){
div[i].style.display="none";
input[i].className="";
}
//this代表当前事件的元素,将选中的内容显示出来
this.className="active";
div[this.index].style.display="block";
}
}
};
</script>
</head>
<body>
<div id="div1">
<input class="active" type="button" value="服装">
<input type="button" value="化妆">
<input type="button" value="饰品">
<input type="button" value="食物">
<div style="display: block">1111</div>
<div>222</div>
<div>3333</div>
<div>4444</div>
</div>
</body>
</html>
效果图如下所示: