JavaScript实现广告倒计时和跳过广告

倒计时和跳过广告

最近打开手机上的app,映入眼帘的都是一个几秒的广告,带有倒计时,当然如果不喜欢的话可以点击跳过,跳过广告其实质应该就是关闭广告。以前用JavaScript做过一个定时关闭的广告,于是把代码完善了一下,加上倒计时效果和实现跳过部分的代码。
在这里插入图片描述

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>定时关闭的广告</title>
		<style type="text/css">
			.main img {
    
    
				width: 100%;
			}
			.adv {
    
    
				position: absolute;
				z-index: 9;
				width: 616px;
				height: 395px;
				top: 0;
				left: 0;
				bottom: 0;
				right: 0;
				margin: auto;
			}

			.adv .right {
    
    
				position: absolute;
				right:0;
				top:10px;
				font-size: 14px;
				color:#fff;
				cursor: pointer;
				background-color: #333;
				border-radius: 10px;
				width: 80px;
				height: 30px;
				line-height: 30px;
				text-align: center;
			}
		</style>
	</head>
	<body>
		<div class="main">
			<img src="images/gugong.png">
		</div>
		<div class="adv">
			<div class="right">
				<span id="counting">5</span>秒跳过
			</div>
			<div><img src="images/adv.png" alt=""></div>
		</div>
		<script>
		//关闭广告窗口
			function closeAdv() {
    
    
				document.querySelector('.adv').style.display = "none";
			}
			//秒数
			var seconds = document.querySelector("#counting").innerText;
			//定义倒计时函数
			function countDown() {
    
    
				seconds--;
				document.querySelector("#counting").innerText = seconds;
			}
			var count = setInterval(countDown, 1000)
			//每隔一秒检查一次秒数是否为0,若为0,关闭广告窗口,清除定时器
			setInterval(function() {
    
    
				if (seconds == 0) {
    
    
					closeAdv();
					clearInterval(count);
				}
			}, 1000)
			//点击跳过,关闭广告窗口
			var skip = document.querySelector('.right');
			skip.addEventListener('click',closeAdv)
		</script>

	</body>
</html>

猜你喜欢

转载自blog.csdn.net/wangyining070205/article/details/132766336