本文章用js来简化html的代码,当然也可以用本方法来渲染内容。
一般来说我们可以只用html代码来完成下面的简单的框架:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0px;
padding: 0px;
box-sizing:border-box;
}
.box{
width: 800px;
height: 450px;
/* background-color: orange; */
}
.box ul{
display: flex;
/* 水平方向上 */
justify-content: space-evenly;
flex-wrap: wrap;
/* 垂直方向上 */
/* align-content: ; */
}
.box li{
margin-bottom: 45px;
list-style: none;
width: 250px;
height: 180px;
background-color:wheat;
transition: all .5s;
}
.box li:hover{
transform: translate(5px,5px);
box-shadow: 2px 2px 2px 2px rgba(0,0, 0, 0.3);
}
</style>
</head>
<body>
<div class="box">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>
</body>
</html>
但是我们发现,这个li标签没有任何的区别,所有接下来用js来简化html的结构。
基本思路是这样的:
- 获取ul对象(父节点)
- 添加li对象(子节点)
- 父节点中添加子节点(父.appendChild(子))
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0px;
padding: 0px;
box-sizing:border-box;
}
.box{
width: 800px;
height: 450px;
/* background-color: orange; */
}
.box ul{
display: flex;
/* 水平方向上 */
justify-content: space-evenly;
flex-wrap: wrap;
/* 垂直方向上 */
/* align-content: ; */
}
.box li{
margin-bottom: 45px;
list-style: none;
width: 250px;
height: 180px;
background-color:wheat;
transition: all .5s;
}
.box li:hover{
transform: translate(5px,5px);
box-shadow: 2px 2px 2px 2px rgba(0,0, 0, 0.3);
}
</style>
</head>
<body>
<div class="box">
<ul>
</ul>
</div>
<script>
// 找到父节点:ul
const ul = document.querySelector('.box ul')
for(let i = 0;i < 6;i++){
// 生成子节点:li
const li = document.createElement('li')
li.innerHTML = i+1
ul.appendChild(li)
}
</script>
</body>
</html>
两个图的效果都是一模一样的,本案例比较简单,所以便捷性可能没有那么明显,但一看就懂,后续我会出js渲染,请持续关注。