利用jQuery的计数器

发布于 2021-12-11  321 次阅读


<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<style type="text/css">
	*{
		padding: 0;
		margin: 0;
	}
	    .num {
	      margin-top:20px;
		  margin-left: 20px;
	      height: 100%;
		  width: 160px;
	      display: flex;
	      border-radius: 4px;
	      overflow: hidden;
	      box-shadow: 4px 4px 4px #adadad;
	      border: 1px solid #c7c7c7;
	      background-color: #c7c7c7;
	    }
	    .num button {
	      width: 50px;
	      height: 100%;
	      font-size: 30px;
		  line-height: 40px;
	      color: #000;
	      cursor: pointer;
	      border: none;
	      outline: none;
	      background-color:rgba(0, 0, 0, 0);
	    }
	    .num span {
	      height: 100%;
	      font-size: 20px;
	      flex: 1;
	      text-align: center;
	      line-height: 40px;
	      font-family:auto;
	      background-color: white;
	    }
	</style>
	<body>
		<div class="num">
			<!-- - -->
			<button type="button">-</button>
			<!-- 内容 -->
			<span>0</span>
			<!-- + -->
			<button type="button">+</button>
		</div>
	</body>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js" type="text/javascript" charset="utf-8"></script> 
	<script type="text/javascript">
	// +
		$('.num button:last-child').click(function(){
			let num=$('.num span').text()
			num++
			$('.num span').text(num)
		})
	// -
		$('.num button:first-child').click(function(){
			let num=$('.num span').text()
			if(num>0){
			num--
			$('.num span').text(num)
			}else{
				alert('不能再点了')
			}
		})
	</script>
</html>
效果图