目标效果:点击标签1,如果列表标签的style的display是block,改成none,否则改成block,来达到展开收缩菜单效果

一.准备阶段

html文件

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</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>

运行后页面效果

js之展开收缩菜单,用到window.onload ,onclick,-LMLPHP

二.:点击标签1隐藏列表

方法1

html代码

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="box">
<p id="btn" onclick="document.getElementById('ull').style.display='none'">标签1</p>
<ul id="ull" style="display: block;">
<li><a href="#">手写</a></li>
<li><a href="#">拼音</a></li>
</ul>
</div>
</body>
</html>

效果从上图到下图

js之展开收缩菜单,用到window.onload ,onclick,-LMLPHP

方法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>

效果如下

js之展开收缩菜单,用到window.onload ,onclick,-LMLPHP

js之展开收缩菜单,用到window.onload ,onclick,-LMLPHP

05-11 19:54