js之展开收缩菜单,用到window.onload ,onclick,
目标效果:点击标签1,如果列表标签的style的display是block,改成none,否则改成block,来达到展开收缩菜单效果
一.准备阶段
html文件
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <div id="box"> 9 <p id="btn">标签1</p> 10 <ul id="ull" style="display: block;"> 11 <li><a href="#">手写</a></li> 12 <li><a href="#">拼音</a></li> 13 </ul> 14 </div> 15 </body> 16 </html>
运行后页面效果
二.:点击标签1隐藏列表
方法1
html代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <div id="box"> 9 <p id="btn" onclick="document.getElementById('ull').style.display='none'">标签1</p> 10 <ul id="ull" style="display: block;"> 11 <li><a href="#">手写</a></li> 12 <li><a href="#">拼音</a></li> 13 </ul> 14 </div> 15 </body> 16 </html>
效果从上图到下图
方法2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function tonone() { document.getElementById('ull').style.display='none'; } </script> </head> <body> <div id="box"> <p id="btn" onclick="tonone()">标签1</p> <ul id="ull" style="display: block;"> <li><a href="#">手写</a></li> <li><a href="#">拼音</a></li> </ul> </div> </body> </html>
方法3
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> window.onload=function () { document.getElementById('btn').onclick=function () { document.getElementById('ull').style.display='none'; } } </script> </head> <body> <div id="box"> <p id="btn" >标签1</p> <ul id="ull" style="display: block;"> <li><a href="#">手写</a></li> <li><a href="#">拼音</a></li> </ul> </div> </body> </html>
方法4
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> window.onload=function () { var obtn = document.getElementById('btn'); var oull = document.getElementById('ull'); obtn.onclick=function () { oull.style.display='none'; } } </script> </head> <body> <div id="box"> <p id="btn" >标签1</p> <ul id="ull" style="display: block;"> <li><a href="#">手写</a></li> <li><a href="#">拼音</a></li> </ul> </div> </body> </html>
在方法4基础上加上if判断就可以实现页面展开收缩菜单功能
代码如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> window.onload=function () { var obtn = document.getElementById('btn'); var oull = document.getElementById('ull'); obtn.onclick=function () { if(oull.style.display=='none') { oull.style.display='block' } else { oull.style.display='none' } } } </script> </head> <body> <div id="box"> <p id="btn" >标签1</p> <ul id="ull" style="display: block;"> <li><a href="#">手写</a></li> <li><a href="#">拼音</a></li> </ul> </div> </body> </html>
效果如下