原生JavaScript淡入淡出效果

效果:

在这里插入图片描述

代码:

<!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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值