使用style.display = “block”竟然出现“Uncaught TypeError: Cannot set property ‘display’ of undefined”的错误提示,原因是document.getElementsByClassName获取的是一个数组,因而无法直接对数组进行些操作。而通过document.getElementById则获取到的是一个对象。style.display操作的是节点集合,要想使用style.display就要写成XX[0].style.display = “block”,以下是一个错误的例子,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>菜单</title> <style> ul { padding: 0; margin: 0; } li { list-style: none; } .lis { display: block; position: relative; list-style: none; width: 80px; height: 30px; border: 1px solid #333; color: #FFF; background-color: #333; } .lis a { display: block; text-decoration: none; color: #fff; text-align: center; line-height: 30px; } .nav { border: 1px solid #f2f2f2; width: 80px; height: 90px; position: absolute; display: none; top: 30px; left: -1px; } .nav li { text-align: center; line-height: 30px; color: #000; } .nav li:hover { background-color: #f2f2f2; } </style> </head> <body> <ul> <li class="lis"> <a href="#" id="mi">菜单</a> <ul class="nav"> <li>菜单一</li> <li>菜单二</li> <li>菜单三</li> </ul> </li> </ul> <script> var a = document.getElementsByClassName('lis'); var b = document.getElementsByClassName('nav'); var c = document.getElementById('mi'); a.onmouseover = show; a.onmouseout = hide; function show() { b.style.display = "block"; c.style.backgroundColor = '#5e5e5e'; } function hide() { b.style.display = ""; c.style.backgroundColor = '#333'; } </script> </body> </html>
以上写法运行时提示出错,所以改成以下写法即可以正常运行。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>菜单</title> <style> ul { padding: 0; margin: 0; } li { list-style: none; } .lis { display: block; position: relative; list-style: none; width: 80px; height: 30px; border: 1px solid #333; color: #FFF; background-color: #333; } .lis a { display: block; text-decoration: none; color: #fff; text-align: center; line-height: 30px; } .nav { border: 1px solid #f2f2f2; width: 80px; height: 90px; position: absolute; display: none; top: 30px; left: -1px; } .nav li { text-align: center; line-height: 30px; color: #000; } .nav li:hover { background-color: #f2f2f2; } </style> </head> <body> <ul> <li class="lis"> <a href="#" id="mi">菜单</a> <ul class="nav"> <li>菜单一</li> <li>菜单二</li> <li>菜单三</li> </ul> </li> </ul> <script> var a = document.getElementsByClassName('lis')[0]; var b = document.getElementsByClassName('nav')[0]; var c = document.getElementById('mi'); a.onmouseover = show; a.onmouseout = hide; function show() { b.style.display = "block"; c.style.backgroundColor = '#5e5e5e'; } function hide() { b.style.display = ""; c.style.backgroundColor = '#333'; } </script> </body> </html>