在面试的时候,有可能会让用原生js去处理html搭建啊…等一些简单的业务处理,今天我就小小根据一段js代码来搭建了一个html的框架,下面就一起来学习一下吧!
css的代码
html,body{
margin: 10% 10%;
}
.wraper {
width: 500px;
height: 300px;
position: relative;
}
.wraper>img {
width: 500px;
height: 300px;
display: none;
}
.circle {
position: absolute;
bottom: 20px;
left: calc(50% - 60px);
}
span {
width: 50px;
height: 30px;
display: inline-block;
line-height: 30px;
text-align: center;
color: red;
background-color: rgba(100, 100, 100, 0.8);
}
.active_circle {
background-color: #ccc;
}
.wraper>.active {
display: block;
}
#pre {
width: 30px;
height: 50px;
background-color: rgba(100, 100, 100, 0.8);
color: #fff;
position: absolute;
left: 0;
top: calc(50% - 25px);
text-align: center;
line-height: 50px;
}
#next {
width: 30px;
height: 50px;
background-color: rgba(100, 100, 100, 0.8);
color: #fff;
position: absolute;
right: 0;
top: calc(50% - 25px);
text-align: center;
line-height: 50px;
}
这里是需要用js处理的代码
var swiper = [
{
title: '女孩1',
img: './img/1.jpg'
},
{
title: '女孩2',
img: './img/2.jpg'
},
{
title: '女孩3',
img: './img/3.jpg'
}, {
title: '女孩4',
img: './img/4.jpg'
}
]
用原生js搭建html 首先我们要知道用那些属性来创建,我一起去认识一下。
- document.createElement()创建元素节点(指的是创建标签)
- document.body.appendChild()插入节点【插入标签】它要通过父元素进行操作,它跟push类似都是从后面一次插入的
好了接下来我们看js是如何操作的
// 用js搭建的html框架
var wraper=document.createElement('div')
document.body.appendChild(wraper)
wraper.className='wraper'
var wraper = document.getElementsByClassName('wraper')[0]
//这是创建img并给img插入获取的img的地址
for (var i = 0; i < swiper.length; i++) {
swiper[i].img
var img = document.createElement('img')
wraper.appendChild(img)
img.src = swiper[i].img
}
var pr = document.createElement('div')
var ne = document.createElement('div')
wraper.appendChild(pr)
wraper.appendChild(ne)
//这是用打点的方式来进行添加内容的像className id都可以用打点的方式来添加css的属性
pr.id = 'pre'
ne.id = 'next'
//这是对标签添加内容
pr.innerHTML = '<'
ne.innerHTML = '>'
var cle = document.createElement('div')
wraper.appendChild(cle)
cle.className = 'circle'
//这是用插入需要的span标签
for (var x = 0; x < swiper.length; x++) {
var span = document.createElement('span')
cle.appendChild(span)
span.innerHTML=swiper[x].title
}
//这是来获取span标签
var span = document.getElementsByTagName('span')[0]
//这是给span标签添加属性
span.className = 'active_circle'
最后实现的HTML框架是这样的,请看图片
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191212222708330.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dnYW94aWFu,size_16,color_FFFFFF,t_7