skip to content
寻找莉莉丝

JS 的排他思想

/ 3 min read / 次阅读

一、前言

Tab栏效果切换是常见的功能需求,它实际上运用的就是JS的排他思想。

那么,什么是排他思想呢?

简而言之,就是在监听成立时,先把所有的样式清除为空,随后按照需求添加需要的样式。

二、案例分析

1. 需求分析

鼠标放到上面的li上,li本身变色(添加类),对应的span也显示出来(添加类);

2. 功能实现

思路:1.点亮盒子。 2.利用索引值显示盒子。

步骤:

  • 1.获取事件源和相关元素
  • 2.绑定事件
  • 3.书写事件驱动程序(排他思想)

HTML:

<div id="box" class="active">
	<ul>
		<li>鞋子</li>
		<li>袜子</li>
		<li>帽子</li>
		<li>裤子</li>
		<li>裙子</li>
	</ul>
	<div class="clearfix"></div>
	<span class="show">鞋子</span>
	<span>袜子</span>
	<span>帽子</span>
	<span>裤子</span>
	<span>裙子</span>
</div>

CSS:

* {
	margin: 0;
	padding: 0;
}
li {
	list-style: none;
}
.clearfix {
	clear: both;
}
#box {
	width: 450px;
	height: 500px;
	background-color: #333;
	margin: 100px auto;
	border: 1px solid #ccc;
	text-align: center;
}
#box ul {
	width: 450px;
	height: 50px;
	text-align: center;
}
#box ul li {
	width: 60px;
	float: left;
	color: #eee;
	background-color: #333;
	font-size: 25px;
	line-height: 50px;
	padding: 5px 15px;
	cursor: pointer;
}
#box ul li:hover {
	color: #333;
	background-color: #ccc;
}
#box.active {
	background-color: #ccc;
}
#box span {
	display: none;
	width: 450px;
	height: 440px;
	font-size: 50px;
	line-height: 440px;
}
#box .show {
	display: block;
}

JS:

window.onload = function () {
	//1.获取事件源和相关元素
	var liArr = document.getElementsByTagName("li");
	var spanArr = document.getElementsByTagName("span");
	//2.绑定事件
	for (var i = 0; i < liArr.length; i++) {
		//3.书写事件驱动程序(排他思想)
		liArr[i].index = i;
		liArr[i].onmouseover = function () {
			for (var j = 0; j < spanArr.length; j++) {
				// 清除所有样式
				liArr[j].classList = "";
				spanArr[j].classList = "";
			}
			// 添加需要的样式
			this.classList = "active";
			spanArr[this.index].className = "show";
		};
	}
};

三、小结

遇到此类需求时(TAB切换),第一反应就是要想到“排他思想”。

关键分两步走,第一步当事件监听时,用for循环遍历所有li元素和span元素,并清空其所有样式;

第二步,跳出循环,按照需求分别添加样式。