版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/qq_31699845/article/details/80633961
实现下拉列表
实现效果如图:
主要注意一下enevt事件,同时因为感觉select原生的样式不容易修改,因此自己写了一个下拉列表,便于修改样式。
直接上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义下拉列表</title>
<style>
html,
body {
height: 100%;
}
.select {
width: 200px;
background: #ccc;
font-size: 14px;
position: relative;
}
.clearfix {
/* 清楚浮动 */
content: "";
display: table;
clear: both;
}
.select div {
height: 30px;
/* 这个貌似对span有效,但是对于input没有效果 */
line-height: 30px;
}
.select div span {
/* 这里如果使用inline-block,inline-block会多一点间距,还是使用block+float来进行布局 */
display: block;
text-align: center;
float: left;
font-size: 12px;
width: 50px;
}
.select div input {
width: 150px;
display: block;
float: left;
/* 默认的input包含一些padding border */
box-sizing: border-box;
/* 设置高度和外层div的高度一致,这样看起来才像是垂直居中显示 */
height: 30px;
}
.select ul {
position: absolute;
/* list-style-type: none; */
background: #aaa;
/* 去掉默认的样式以及margin padding */
list-style: none;
margin: 0;
padding: 0;
/* 如果设置了position,那么这里的100%可能是相对与html而言的,但是这里设置了select的position,所以这里的宽度是相对于select而言 */
/* width: 100%; */
width: 150px;
box-sizing: border-box;
/* 避免被遮住 */
z-index: 100;
text-align: center;
left: 50px;
/* 默认是隐藏的 */
display: none;
}
.select ul li {
line-height: 1.4rem;
border-bottom: 1px solid #ccc;
cursor: pointer;
}
.select ul li:hover {
/* 悬浮的时候显示背景颜色 */
color: red;
}
</style>
</head>
<body onclick="closeLists()">
<div class="select">
<div class="clearfix">
<span>事件类型</span>
<input type="text" readonly onclick="showList()" id="Etype">
</div>
<ul id="lists">
<li onclick="chooseParam()">爆炸事故</li>
<li onclick="chooseParam()">火灾事故</li>
<li onclick="chooseParam()">中毒事件</li>
<li onclick="chooseParam()">坍塌事故</li>
</ul>
</div>
<script>
function showList() {
document.getElementById("lists").style.display = "block";
// let ev = event || window.event;
event.stopPropagation()
}
function chooseParam() {
// console.log(event)
document.getElementById("Etype").value = event.target.innerText;
}
function closeLists() {
document.getElementById("lists").style.display = "none";
event.stopPropagation(); //阻止冒泡
}
</script>
</body>
</html>