1. 程式人生 > >原生javascript實現TAB切換

原生javascript實現TAB切換

所謂TAB切換就是類似於淘寶,京東左側購物欄那種樣式。

1.html:

<!DOCTYPE html>
	<head>
		<meta content="text/html;charset=utf-8">
		<title>tab切換</title>
		<link rel="stylesheet" href="css/index.css" type="text/css"/>
	</head>
	<body>
		<div id="wrap">
			<div id="left">
				<ul id="leftList">
					<li>標題1</li>
					<li>標題2</li>
					<li>標題3</li>
					<li>標題4</li>
					<li>標題5</li>
				<ul>
			</div>
			<div id="right">
				<div>1</div>
                                <div>2</div>
                                <div>3</div>
                                <div>4</div>
                                <div>5</div>
			</div>
		</div>
	</body>
	<script src="js/index.js"></script>
</html>

2.css樣式

*{
	margin:0;
	padding:0;
}
#wrap{
	width:500px;
	min-width:500px;
	height:252px;
	overflow:hidden;
}
#left{
	width:40%;
	height:100%;
	background-color:red;
	border:1px solid red;
	float:left;
	box-sizing:border-box;/*此元素的內邊距和邊框不再會增加它的寬度*/
}
#right{
	width:60%;
	height:100%;
	background-color:yellow;
	border:1px solid red;
	border-left-style:none;
	float:left;
	box-sizing:border-box;/*此元素的內邊距和邊框不再會增加它的寬度*/
	display:none;
}
#leftList{
	list-style:none;
}
li{
	width:100%;
	height:50px;
	background-color:red;
	color:white;
	text-indent:2em;/*段落首行文字縮排2em*/
	line-height:50px;
}
.current{
	background-color:white;
	color:red;
	border-right-style:none;
	border-left:1px solid red;
}
.close{
	display: none;
}

.show{
	width: 100%;
	height: 100%;
	float:left;
	background-color: #CCC;
	text-align: center;
	font-size: 100px;
	color: black;
	display: block;
}

3.js

var wrapDiv=document.getElementById("wrap");
var leftDiv=document.getElementById("left");
var rightDiv=document.getElementById("right");
var lis=document.getElementsByTagName("li");//獲取左側列表
var divs=document.querySelectorAll("#right>div");
/***操作***/
//tab切換
for(var i=0;i<lis.length;i++){
	lis[i].index=i;
	lis[i].onmouseover=function(){
		for(var j=0;j<divs.length;j++){
			lis[j].className="";
			divs[j].className="close";
		}
		this.className="current";
		rightDiv.style.display="block";
		divs[this.index].className="show";
	}
}
//處理事件冒泡
wrapDiv.onmouseout=function (e) {
	if (!e) e = window.event;
	var reltg = e.relatedTarget ? e.relatedTarget : e.toElement;
	while (reltg && reltg != this) reltg = reltg.parentNode;
	if (reltg != this) {
		rightDiv.style.display="none";
		for(var j=0;j<divs.length;j++){
			lis[j].className="";
			divs[j].className="close";
		}
	}
}

            

其中曾出現的bug有,實現滑鼠移出id為wrap這個div時回到最初樣子這個功能時,當從右邊出來時,左邊的div就會消失。經過查詢資料我發現都是冒泡事件搞的鬼。當滑鼠移出移進子元素時,子元素的onmouseover事件和onmouseout事件會觸發,但是它自己沒有這兩個事件啊,就把這兩個事件傳遞給了它的父元素,父元素有這兩個事件所以就發生了我們看到的情況。

    那麼怎樣才能避免這種情況的發生勒?