老师这样对吗
来源:7-2 编程练习
为爱修行
2019-02-28 16:28:46
<!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: #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"> //此处填写代码 (function(){ var wrap={ list:document.querySelector('#list'), li:document.querySelectorAll('li'), btnAdd:document.getElementById('btnAdd'), btnRemove:document.getElementById('btnRemove') }; for (var i = 0; i < wrap.li.length; i++) { wrap.li[i].onmouseover=function(){ this.style.background='purple'; } wrap.li[i].onmouseout=function(){ this.style.background='pink'; } } wrap.btnAdd.onclick=function(){ var len=wrap.list.childElementCount; var newLi=document.createElement('li'); var txt=document.createTextNode('我是li'+(len+1)); newLi.appendChild(txt); wrap.list.appendChild(newLi); } wrap.btnRemove.onclick=function(){ if(wrap.list.childElementCount>0){ wrap.list.removeChild(list.lastElementChild); } } })(); </script> </body> </html>
1回答
你好,测试了代码,添加和删除元素是没有问题的,但是当原本有的元素删除之后,点击按钮添加元素,新添加的元素(前三个)鼠标移入的时候背景颜色没有改变。改变背景颜色的代码可以封装一下,在添加元素之后可以继续调用。
自己试着完善下吧,祝学习愉快!
相似问题