<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
*{margin:0;padding:0;}
input{width:50px;height:30px;background:#ccc;border-radius: 50%;}
div{display:none;width:250px;height:200px;background:#f90;font-size:30px;font-weight:bold;text-align:center;line-height:200px;border-radius:5px;}
.active{width:70px;background:tomato;}
.show{background:#f90;color:#fff;display:block;}
</style>
<script>
window.onload = function ()
{
var aBtn = document.getElementsByTagName('input');
var aDiv = document.getElementsByTagName('div');
for (var i=0;i<aBtn.length;i++) {
//为了创建关联条件的时候自己定义的属性
aBtn[i].setAttribute('dataindex',i);
//给每一个按钮加上点击事件
aBtn[i].onclick = function ()
{
//先清空所有的按钮的class name
for (var i=0;i<aBtn.length;i++) {
aBtn[i].className = '';
aDiv[i].className = '';
}
var index = this.getAttribute('dataindex');
aDiv[index].className = 'show';
//它是跟你当前点击的那个按钮添加class
this.className = 'active';
}
}
}
</script>
</head>
<body>
<input type="button" value="中国" class="active"/>
<input type="button" value="美国" />
<input type="button" value="英国" />
<input type="button" value="德国" />
<div class="show">北京</div>
<div>华盛顿</div>
<div>伦敦</div>
<div>柏林</div>
</body>
</html>
重点内容
本文章和‘js中选项卡的简单实现1’的主要区别在于定义自定义属性时的反方式不同,本文章
定义是用的aBtn[i].setAttribute(‘dataindex’,i);
得到用的是var index = this.getAttribute(‘dataindex’);