前端下拉列表的實現
阿新 • • 發佈:2018-11-11
實現下拉列表
實現效果如圖:
主要注意一下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: 12 px;
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>