JS案例——计数

使用js语句实现计数功能:
默认鼠标每次点击window区域无效
当点击开始计数后:鼠标每次点击window区域 计数+1
点击停止计数后:鼠标每次点击window区域无效

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<p>当前点击<span id="span">0</span>次</p>
		<button type="button">开始计数</button>
		<button type="button">停止计数</button>
		
		<script type="text/javascript">
			// 设置开始计算按钮事件
			document.getElementsByTagName("button")[0].onclick=function(e){
				// 阻止事件向外部执行,即点击开始按钮时不会加1,只有点击window才会开始加1
				e.stopPropagation();
				// 窗口点击事件
				window.onclick=function(){
					let i=parseInt(document.getElementById("span").innerText);
					document.getElementById("span").innerText=i+1;
					
				}
			} 
			// 设置停止计数按钮事件
			document.getElementsByTagName("button")[1].onclick=function(){
				window.onclick=null;
			}
		</script>
	</body>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41828603/article/details/88595226