天天看點

原生js寫緩慢下拉菜單

今天想寫個原生js緩慢下拉菜單 中間一直出bug 琢磨了許久 終于實作了跟 jquery的slideToggle() 差不多的效果

先看效果

原生js寫緩慢下拉菜單

把樣式結構先寫好

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>原生js緩慢下拉菜單-by:小鑫 QQ:857525554</title>
	<style>
	    ul,li {
	    	list-style: none;
	    	margin: 0;
	    	padding: 0;
	    }
		.btn {
			width: 120px;
			height: 35px;
			margin: 0 auto;
			background: #333;
			color: #fff;
			text-align: center;
			line-height: 35px;
			border-radius: 3px;
		}

		.menu {
			width: 120px;
			height: 0px;
			margin: 5px auto;
			background: #E60026;
			overflow: hidden;
		}

		.menu a {
			display: block;
			text-align: center;
			line-height: 30px;
			color: #fff;
			text-decoration: none;
		}
	</style>
</head>
<body>
	<ul>
		<li class="btn">點我
			<ul class="menu">
				<li><a href="#">菜單一</a></li>
				<li><a href="#">菜單二</a></li>
				<li><a href="#">菜單三</a></li>
			</ul>
		</li>
	</ul>
</body>
</html>
           

接下來是js腳本

<script>
	var btn = document.getElementsByTagName('li')[0],
	    t_over,
	    t_leave,
	    menu = btn.getElementsByTagName('ul')[0],
	    h = menu.offsetHeight;
	btn.onmouseover = function() {
		clearTimeout(t_leave);
		add();
	}
	btn.onmouseout = function() {
		clearTimeout(t_over);
		sub();
	}
	function add() {
		h += 1;
		if (h <= 100) {
			menu.style.height = h + 'px';
			t_over = setTimeout(add,10);
		}else {
			return;
		}
		console.log(h)
	}
	function sub() {
		h -= 1;
		if (h > 0) {
			menu.style.height = h + 'px';
			t_leave = setTimeout(sub,10);
		}else {
			menu.style.height = '0px'
			return;
		}
	}
</script>
           

這段js腳本中 最關鍵的地方是 clearTimeout() 清除定時器這裡 如下:

btn.onmouseover = function() {
	    // 滑鼠劃過的時候 清除向上的定時器
		clearTimeout(t_leave);
		add();
	}
	btn.onmouseout = function() {
		clearTimeout(t_over);
		sub();
	}
           

你可以試着把那兩個清除定時的删掉 然後在快速的劃過按鈕 會有意想不到的結果的。

繼續閱讀