一 . ###创建标签其原理就是
- 创建一个节点;
- var x = document.createElement("TagName")
- 赋予节点样式;
- x.setAttribute("class",类名)
- 对节点进行赋值;
- x.innerHTML = 内容 //赋值
- 添加节点到父元素
- 要添加到的元素.appendChild(x);
二. 样式图:
三. 主要代码流程:
<div class="container">
<h3 style="text-align: center">单击下面得"添加"按钮添加标签</h3>
<div class="dispanel" id="box"></div>
<button class="btn" id="btn1">全部清除</button>
<ul id="ul">
<li><span>John Doe1</span> <button class="clibtn btn">添加</button></li>
<li><span>John Doe2</span> <button class="clibtn btn">添加</button></li>
<li><span>John Doe3</span> <button class="clibtn btn">添加</button></li>
<li><span>John Doe4</span> <button class="clibtn btn">添加</button></li>
<li><span>John Doe5</span> <button class="clibtn btn">添加</button></li>
<li><span>John Doe6 </span><button class="clibtn btn">添加</button></li>
</ul>
</div>
body{
margin:0 ;
padding:0;
background-color:#002F4F;
color: #ffffff;
font-family: "微软雅黑";
font-size: 1em;
}
ul,h3{margin: 0;
list-style: none;
padding: 0px}
.container{
width:300px;
height:350px;
margin: 50px auto;
}
.dispanel{
width: 290px;
height:50px;
background-color: #ffffff;
margin: 0 auto;
}
.btn{
width:100px;
height:20px;
color: #ffffff;
background-color:red;
border: 0px;
font-size: 1em;
margin:10px 0 10px 5px;
}
.container ul li{
width:300px;
height:30px;
margin-top:10px;
}
.spanstyle{display: inline-block;
color:#000;
width:85px;height:22px;
background-color: bisque;
margin-left:5px;
font-size: 12px;
text-align: center;
line-height: 22px;
}
var oUl = document.getElementById("ul");
var oBtn = oUl.getElementsByClassName("btn");
var oLi = document.getElementsByClassName("li");
var oBox = document.getElementById("box");
for(var i = 0;i<oBtn.length;i++) {
oBtn[i].onclick = function () {
var oA = document.createElement("span"); //创建一个节点Node
var oNew = oA.setAttribute("class", "spanstyle"); //将节点上增加class样式
var ospan = this.previousElementSibling.innerHTML + " X"; //this == oBtn[i] / previousElementSiling:上一个元素的兄弟节点 即 <span>
oA.innerHTML = ospan; //将ospa的值付给新创建的节点Node oA.
oBox.appendChild(oA); //将oA 添加为oBox的儿子
oA.onclick=function () {
oBox.removeChild(oA); //移除这个元素
}
}
}
var obtn1 = document.getElementById("btn1");
obtn1.onclick=function () {
oBox.innerHTML=""; //清除内容
}