<script> 标签中找不到 items 变量的定义。应该使用 document.getElementsByClassName('item') 来获取所有类名为 item 的元素。此外,在 CSS 中 width 属性后有一个多余的冒号 :,应该删除。修改后的代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<style>
			.item{
				width: 100px;
				height: 50px;
				border: solid 1px rgb(42,156,156);
				float: left;
				margin-right: 10px;
			}
		</style>
		<div class="box">
			<h2 class="page-header">点击切换颜色</h2>
			<div class="item"></div>
			<div class="item"></div>
			<div class="item"></div>
		</div>
		
		
		<script>
			let items=document.getElementsByClassName('item');
			
			for(var i=0;i<items.length;i++){
				items[i].onclick=function(){
					this.style.background='yellow'
				}
			}
		</script>
	</body>
</html>
``
!DOCTYPE htmlhtml	head		meta charset=UTF-8		titletitle	head	body		style			item				width 100px;				height 50px;				border solid 1px rgb42156156;				float left;				margin-right 10px;					style		div clas

原文地址: https://www.cveoy.top/t/topic/eZhS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录