本文实例为大家分享了Javascript实现下拉列表的具体代码,供大家参考,具体内容如下
这一次写了一个比较简单的下拉列表的实现,点击出现列表内容,再次点击列表消失,研究了很久,发现这种js写法确实比较好用。先看一下效果。
直接上代码,js是主要写的部分,css是随意调试的,不过这个写法要用到css。
1、HTML部分的代码
第一
- a
- b
- c
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
2、css部分的代码
.outer{
margin: 0 auto;
width: 500px;
height: 600px;
border: 1px solid red;
}
.outer .inner{
width: 500px;
border: 1px solid red;
}
.outer .inner ul{
list-style: none;
border: 1px solid fuchsia;
}
h2{
border: 1px solid blueviolet;
height: 30px;
display: flex;
justify-content: center;
cursor: pointer;
background-color: #74a400;
margin: 0;
}
ul{
display: none;
}
这里.ul是HTML里面没有的,要通过js来添加
.ul{
display: block;
background-color: cornflowerblue;
margin: 0;
}
ul li{
border: 1px solid cornflowerblue;
background-color: darkgray;
display: flex;
justify-content: center;
margin-left: -42px;
cursor: pointer;
}
3、最重要的js代码部分
window.onload = function () {
// 获取h2与ul
var h2 = document.getElementsByTagName("h2");
var ul = document.getElementsByTagName("ul");
//对所有的h2绑定一个点击事件
for (let i = 0; i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



