使用js创建10*10方块

使用li标签创建10*10方块,颜色不一样。

效果如图所示:

创建ul来装乘li,用for循环套for循环来创建方块,并利用奇偶性来赋给颜色。最后给他添加位置。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="author" content="白小白">
<title>方格</title>
<style>
*{
margin: 0;
padding: 0;
}
ul li {
margin: 0;
padding: 0;
list-style: none;
}
#bg{
200px;
height: 200px;
position: relative;
border: solid 1px #000;
}
.bai{
background:white;
20px;
height: 20px;
position: absolute;
}
.hei{
background:#000;
20px;
height: 20px;
position: absolute;
}

</style>
</head>
<body>
<ul id="bg">


<ul>
</body>
<script>

//容器ul

var bg = document.querySelector('#bg');

//开始for循环创建li
for(var i = 0 ; i < 10; i++){
for(var j = 0; j < 10;j ++ ){
var li = document.createElement('li');

//利用奇偶性来赋颜色

if( i % 2 == 0){
if(j % 2 == 0){
li.className = 'hei';
}else{
li.className = 'bai';
}
}else{
if(j % 2 == 0){
li.className = 'bai';
}else{
li.className = 'hei';
}
}
bg.append(li);

//添加位置
li.style.top = i * 20 + "px";
li.style.left = j * 20 + "px";
}
}


</script>

</html>

原文地址:https://www.cnblogs.com/baipengzhen/p/6481896.html