根据效果图,实现如下图所示效果!
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
html,
body {
margin: 0;
padding: 0;
}
div:not(:nth-of-type(2)) {
width: 500px;
height: 100%;
background-color: #a0e4ff;
margin: 0 auto;
}
/*ul默认有外边距*/
ul {
width: 300px;
height: 100%;
background-color: #ecc7ea;
list-style: none;
/*清除默认边距*/
margin: 0;
padding: 0;
margin: 20px auto;
margin-bottom: 30px;
}
li {
width: 200px;
height: 30px;
line-height: 30px;
margin: 30px auto;
background-color: #cdffc0;
}
</style>
</head>
<body>
<div id="box">
<button id="btnAdd">添加元素</button>
<button id="btnRemove">删除元素</button>
<ul id="list">我是ul
<li>我是li1</li>
<li>我是li2</li>
<li>我是li3</li>
</ul>
</div>
<script type="text/javascript">
//此处填写代码
var btnAdd = document.getElementById("btnAdd"); //添加按钮
var btnRemove = document.getElementById("btnRemove"); //删除按钮
var list = document.getElementById("list"); //ul列表
var li = document.getElementsByTagName("li"); //获取li数组
//鼠标移入移出li背景色变色
for (var i = 0,len=li.length;i<len; i++) {
if(i<3){
li[i].onmouseover=function(){
this.style.backgroundColor='#009fff';
}
li[i].onmouseout=function(){
this.style.backgroundColor='#df8063';
}
}
}
//li添加事件
btnAdd.onclick=function(){
var li = document.createElement("li");
var txt = document.createTextNode("我是li"+(list.children.length+1));
li.appendChild(txt);
list.appendChild(li);
}
//li删除事件
btnRemove.onclick=function(){
if(list.children.length==0){
return;
}
else{
list.removeChild(list.lastChild);
}
}
</script>
</body>
</html>