使用js仿写一个原生下拉列表框
直接上代码,有注释
这里在选择那里额外加了一个小图片
目录截图

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>使用js仿写一个原生下拉列表框</title>
<style>
li,ul{
list-style: none;
margin: 0;
padding: 0;
}
.btn{
position: relative;
display: block;
height: 40px;
}
.btn,.box{
margin: 0 auto;
width: 100px;
text-align: center;
background-color: skyblue;
line-height: 40px;
user-select: none;
}
.box{
display: none;
}
.box li{
border-top: 1px solid #eee;
overflow: hidden;
}
.box li:hover{
background-color: #ffffff;
color: black;
}
.btn img{
position: absolute;
right: 5px;
top: 12px;
width: 16px;
height: 16px;
transition: all 0.5s ease;
}
</style>
</head>
<body>
<span class="btn">请选择<img class="icon" src="./img/top.png"></img></span>
<div class="box">
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JAVASCRIPT</li>
<li>C</li>
<li>C++</li>
<li>C#</li>
</ul>
</div>
<script>
let btn=document.querySelector('.btn')
let box=document.querySelector('.box')
let lis=document.querySelectorAll('li')
let icon=document.querySelector('.icon')
box.style.display='none'
function slideDown(){
let startHeight=0,endHeight=40
let timer=setInterval(function(){
startHeight++
lis.forEach(item => {
item.style.height=startHeight+'px'
});
if(startHeight>=endHeight){
clearInterval(timer)
}
},10)
setTimeout(function(){
box.style.display='block'
},100)
}
function slideUp(){
let startHeight=40,endHeight=0
let timer=setInterval(function(){
startHeight--
lis.forEach(item => {
item.style.height=startHeight+'px'
});
if(startHeight<=endHeight){
clearInterval(timer)
}
},10)
setTimeout(function(){
box.style.display='none'
},350)
}
btn.addEventListener('click',function(){
if(box.style.display=='none'){
icon.style.transform='rotate(180deg)'
slideDown()
}else{
icon.style.transform='rotate(0deg)'
slideUp()
}
})
</script>
</body>
</html>
作为自己学习过程的小练习,有什么问题和错误欢迎指正