为什么会报错呢
来源:7-2 编程练习
慕丝5187111
2018-11-12 11:03:22
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <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 list = document.getElementById('list'); function mouseStyle() { var li =document.getElementsByTagName('li'); for(var i = 0,len = li.length;i<len;i++){ li[i].onmouseover = function(){ this.style.backgroundColor = "lightblue"; } li[i].onmouseout = function(){ this.style.backgroundColor = "pink"; } } }mouseStyle(); document.getElementById('butAdd').onclick= function () { var m = document.getElementsByTagName('li').length + 1; var newLi = document.createElement('li'); var txt = document.createTextNode("我是li" + m); newLi.appendChild(txt); list.appendChild(newLi); m++; mouseStyle(); } document.getElementById('butRemove').onclick= function () { list.replaceChild(list.lastElementChild); } })(); </script> </body> </html>
1回答
代码中存在单词错误和使用方法错误,如下:
自己可以修改下样式,无论添加元素还是删除元素,只有前三个元素鼠标移入上去可以改变背景颜色,你现在这个代码是全部的li都可以改变。
自己测试下,祝学习愉快!
相似问题