请检查作业,有什么地方需要改进吗?
来源:7-2 编程练习
不会飞的萌物
2019-03-07 20:53:12
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DOM操作</title> <style type="text/css"> html, body { margin: 0; padding: 0; } div:not(:nth-of-type(2)) { width: 500px; height: 100%; background-color: #00c4ff7a; margin: 0 auto; } /*ul默认有外边距*/ ul { width: 300px; height: 100%; background-color: #f9c3e6d6; 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 box = ById('box'), btnAdd = ById('btnAdd'), btnRemove = ById('btnRemove'), ul = ById('list'), li = document.getElementsByTagName('li'); function ById(id){ return typeof(id) === "string" ? document.getElementById(id) : id; } (function moveover(){ for(var i=0;i<li.length;i++){ li[i].onmouseover = function(){ this.style.backgroundColor = "skyblue"; }; li[i].onmouseout = function(){ this.style.backgroundColor = "pink"; }; } })(); (function addItem(){ btnAdd.onclick = function(){ var newli = document.createElement('li'), txt = document.createTextNode("我是li"+(li.length+1)); newli.appendChild(txt); ul.appendChild(newli); }; })(); (function delItem(){ btnRemove.onclick = function(){ if(li.length>2){ ul.removeChild(ul.lastElementChild);} }; })(); </script> </body> </html>
1回答
你好,添加和删除元素效果是正确的,删除元素时可以全部删除,不需要留着两个:
还有鼠标移入元素改变背景颜色需要调整,无论是原来的元素还是删除之后新添加的元素,前三个全部都会改变背景颜色,可以将改变颜色的代码封装起来,在添加元素中进行调用。
自己可以修改完善下,祝学习愉快!
相似问题