1. 程式人生 > 其它 >原生JavaScript淡入淡出效果

原生JavaScript淡入淡出效果

技術標籤:htmlJavaScript

效果:

在這裡插入圖片描述

程式碼:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			* {
				margin: 0;
				padding: 0
			}
			
			body {
				height: 100%;
			}
			
			.box {
				width: 250px;
				height: 100%;
				background-color: rgba(
0, 0, 0, 0.7); position: absolute; left: 0; top: 0; } .box ul { background-color: orange; } .box button { position: absolute; right: -25px; top: 50%; margin-top: -20px; } button { border: 0; background-color: #ccc; width: 25px; height: 40px;
font-size: 24px; user-select: none; outline: none; } ul li { height: 40px; text-align: center; line-height: 40px; border-bottom: 1px solid #aaa; user-select: none; } li:hover { background-color: orangered; color: #fff; } </style> <
/head> <body> <div class="box"> <ul> <li>選單一</li> <li>選單一</li> <li>選單一</li> <li>選單一</li> <li>選單一</li> </ul> <button>></button> </div> <script> var btn = document.getElementsByTagName("button")[0]; var div = document.getElementsByTagName("div")[0]; var timer; var speed = 5; var flag = true; btn.onclick = function() { console.log(div.offsetLeft) if(flag) { speed = -speed; timer = setInterval(function() { if(div.offsetLeft <= -250) { clearInterval(timer); flag = false; return; } div.style.left = div.offsetLeft + speed + "px"; }, 20) } else { speed = -speed; timer = setInterval(function() { if(div.offsetLeft >= 0) { clearInterval(timer); flag = true; return; } div.style.left = div.offsetLeft + speed + "px"; }, 20) } } </script> </body> </html>