<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
#box {
margin-top: 100px;
}
span {
display: inline-block;
width: 100px;
height: 100px;
background: #0F0;
text-align: center;
line-height: 100px;
border-radius: 50%;
}
</style>
</head>
<body>
<input type="text" id="txt"/>
<div id="btn">
<button id="before-add">从前添加</button>
<button id="after-add">从后添加</button>
<button id="before-delete">从前删除</button>
<button id="after-delete">从后删除</button>
</div>
<div id="box"></div>
<script>
/**
* 页面上第一行有一个文本框 四个按钮 分别为 从前添加 从后添加 从前删除 从后删除 每次添加,出现该文本元素 可以通过按钮操作插入和删除元素
*/
var beforeAddBtn = document.getElementById('before-add');
var afterAddBtn = document.getElementById('after-add');
var beforeDeleteBtn = document.getElementById('before-delete');
var afterDeleteBtn = document.getElementById('after-delete');
var boxS = document.getElementById('box');
var txtInput = document.getElementById('txt');
// var span = document.createElement('span');
afterAddBtn.addEventListener('click', function () {
if(txtInput.value != '') {
var span = document.createElement('span');
span.innerHTML = txtInput.value;
boxS.appendChild(span);
txtInput.value = '';
}
});
beforeAddBtn.addEventListener('click', function () {
if(txtInput.value != '') {
var span = document.createElement('span');
span.innerHTML = txtInput.value;
boxS.insertBefore(span, boxS.firstChild);//在第一个元素之前添加span
txtInput.value = '';
}
});
beforeDeleteBtn.addEventListener('click', function () {
if (boxS.childNodes.length) {
boxS.removeChild(boxS.childNodes[0]);//在boxS中删除第一个元素
}
});
afterDeleteBtn.addEventListener('click', function () {
if (boxS.childNodes.length) {
boxS.removeChild(boxS.childNodes[boxS.childNodes.length - 1]);
}
});
</script>
</body>
</html>