<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,minimum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>select封装</title>
</head>
<style>
/**
*自定义下拉框
***/
.select {
color: #333;
display: inline-block;
z-index: 2;
position: relative;
}
.select>div, .select>ul {
width: 21rem;
border-radius: .3rem;
/* border: 1px solid #ccc; */
/* box-shadow: 0 1px 6px 0 rgba(0,0,0,0.15); */
box-sizing: border-box;
position: absolute;
text-align: left;
}
.select>div {
position: relative;
}
.select>ul {
margin: 0;
margin-top: 0rem;
list-style: none;
padding: 0;
display: none;
background: #fff;
}
.select>div, .select>ul>li {
line-height: 250%;
padding-left: .5rem;
padding-right: .5rem;
}
.select>ul>li:hover {
background-color: #0DC;
color: #fff;
}
/* 从父元素定义子元素的样式,比直接在子元素上定义类的样式优先级搞 */
.select>div>div {
width: 1rem;
/* height: .45rem; */
position: absolute;
right: .5rem;
top: 50%;
transform: translateY(-50%);
background-repeat: no-repeat;
}
.arrow-bottom {
background-image: linear-gradient(135deg, transparent 30%, var(--arrow-color) 30%, var(--arrow-color) 40%, transparent 40%), linear-gradient(45deg, transparent 60%, var(--arrow-color) 60%, var(--arrow-color) 70%, transparent 70%);
}
.arrow-top {
background-image: linear-gradient(45deg, transparent 30%, var(--arrow-color) 30%, var(--arrow-color) 40%, transparent 40%), linear-gradient(135deg, transparent 60%, var(--arrow-color) 60%, var(--arrow-color) 70%, transparent 70%);
}
</style>
<body>
<div class="select">
<div><span id="cat">请选择</span>
<div class="arrow-bottom" style="color: #ccc;">></div>
</div>
<ul>
<li data-value="123456">西服</li>
<li data-value="654321">工装</li>
<li data-value="1314520">衬衫</li>
<li data-value="77499981">其他</li>
</ul>
</div>
</body>
</html>
<script>
class CustomSelect {
constructor() {
const select = document.querySelector(".select");
//注意:div的firstChild是他的text,然后才是子节点
this.input = select.firstElementChild;
this.arrow = select.querySelector(".select>div>div");
this.list = select.children[1];
this.value = undefined;
this.setListener();
}
setListener() {
//如果采用这种方法,那么函数内部的this会被修改为触发事件的对象,而不是当前上下文
//this.input.onclick = this.changeExpandState;
this.input.onclick = ()=>{
this.changeExpandState();
}
for(let item of this.list.children) {
item.onclick = ()=>{
this.changeExpandState();
this.value = item.dataset.value;
this.input.firstChild.textContent = item.textContent;
//console.log(this.value);
}
}
}
changeExpandState() {
//注意:.select>ul这种样式是定义在select元素里的,而不是ul,所以当去获取ul的该样式的时候会返回空
if(this.list.style.display === "none" || this.list.style.display === "") {
this.list.style.display = "block";
this.arrow.className = "arrow-top";
} else {
this.list.style.display = "none";
this.arrow.className = "arrow-bottom";
}
}
}
window.onload = function(){
new CustomSelect();
}
</script>