制作四个选项卡页 Tab,用户可以通过切换不同的 Tab 页查看不同类别的新闻信息,每个 Tab 有对应的内容版块,点击某个选项卡时,显示对应的内容版块,隐藏其他内容版块,并且为了突出当前的选项卡,还

查看本章节

查看作业目录


需求说明:

制作四个选项卡页 Tab,用户可以通过切换不同的 Tab 页查看不同类别的新闻信息,每个 Tab 有对应的内容版块,点击某个选项卡时,显示对应的内容版块,隐藏其他内容版块,并且为了突出当前的选项卡,还可以设置其背景样式

实现思路:

  1. 编写 HTML 页面,在页面中添加 Tab、内容版块,以及对应的 CSS 样式
  2. 为每个 Tab 元素添加点击事件,并将 Tab 元素的位置作为参数值传入
  3. 在 JavaScript 脚本中创建点击事件的处理函数
  4. 通过 document 对象找到对应的 Tab 元素及版块内容,并修改其样式
  5. 使用浏览器预览效果

实现代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			h2{
				border-top: solid blue 1px;
				border-left: solid blue 1px;
				border-bottom: solid blue 1px;
				width: 100px;
				height: 35px;
				margin: 0;
				float: left;
				text-align: center;
			}
			.tab-content{
				margin-top: 10px;
				border: solid blue 1px;
				width: 402px;
				height: 400px;
			}
			.tab-content div{
				display: none;
			}
			.current{
				background-color: pink;
			}
			.tab-content .show{
				display: block;
			}
		</style>
	</head>
	<body>
		<div class="tab-head">
			<h2 class="current" onclick="changeTab(0)">热点</h2>
			<h2 onclick="changeTab(1)">娱乐</h2>
			<h2 onclick="changeTab(2)">段子</h2>
			<h2 onclick="changeTab(3)">体育</h2>
		</div>
		<div class="tab-content">
			<div class="show">本页面内容显示热点新闻</div>
			<div>本页面内显示娱乐新闻</div>
			<div>本页面内显示搞笑段子</div>
			<div>本页面内显示体育新闻</div>
		</div>
		<script type="text/javascript">
			var tabs = document.getElementsByClassName("tab-head")[0].getElementsByTagName("h2");
			var contents = document.getElementsByClassName("tab-content")[0].getElementsByTagName("div");
			function changeTab(index){
				for (var i=0;i<tabs.length;i++) {
					if (i==index) {
						tabs[i].className="current";
						contents[i].className="show";
					} else{
						tabs[i].className="";
						contents[i].className="";
					}
				}
			}
		</script>
	</body>
</html>

 

posted @ 2020-11-01 19:47  明金同学  阅读(42)  评论(0编辑  收藏  举报