在不使用ui框架时,原生的select元素可修改的样式非常有限,大多是不满足我们的需求的。因此花了点时间写了个可以自定义样式的select组件,以备以后使用。
1.html
<div id="app" @click="hiddenSelection">
<div class="form_select">
<input
type="text"
v-model="userName"
@click="showAccountList($event)"
/>
<img
src="./arrow-down.svg"
:class="hasClass==='1' ? 'openlist': (hasClass==='0'?'foldlist':'')"
@click="showAccountList($event)"
/>
<ul v-if="isShowUserList">
<li
:class="{'selected':item.selected===true}"
v-for="item in list"
@click="changeUser(item)"
>
{{ item.name }}
</li>
</ul>
</div>
</div>
2.css
#app {
padding: 30px;
}
.form_select {
height: 35px;
display: inline-block;
width: 250px;
position: relative;
color: #aeaeae;
}
input {
width: 100%;
height: 100%;
border: 1px solid #00000040;
border-radius: 4px;
padding: 0 35px 0 15px;
box-sizing: border-box;
color: #aeaeae;
cursor: pointer;
outline: none;
}
input:focus {
border-color: #45abfe;
}
img {
width: 14px;
height: 35px;
right: 15px;
top: 0;
cursor: pointer;
position: absolute;
}
ul {
width: 250px;
background-color: #fff;
border-radius: 4px;
border: 1px solid #e5e5e5;
list-style: none;
padding: 0;
margin-top: 3px;
}
li {
height: 35px;
width: 100%;
padding: 0 15px;
line-height: 35px;
box-sizing: border-box;
cursor: pointer;
}
li:hover {
background-color: #e6f7ff;
color: #737677;
}
li.selected {
background-color: #e6f7ff;
color: #737677;
}
/* 展开: */
.openlist {
-webkit-animation: open 0.3s linear forwards;
animation: open 0.3s linear forwards;
}
/* 收起: */
.foldlist {
-webkit-animation: fold 0.3s linear forwards;
animation: fold 0.3s linear forwards;
}
@-webkit-keyframes open {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(180deg);
}
}
@keyframes open {
from {
transform: rotate(0deg);
}
to {
transform: rotate(180deg);
}
}
@-webkit-keyframes fold {
from {
-webkit-transform: rotate(180deg);
}
to {
-webkit-transform: rotate(0deg);
}
}
@keyframes fold {
from {
transform: rotate(180deg);
}
to {
transform: rotate(0deg);
}
}
3.js
let vm = new Vue({
el: '#app',
data() {
return {
list: [
{
name: '张三',
value: 1,
},
{
name: '李四',
value: 2,
},
{
name: '王五',
value: 3,
},
{
name: '铁柱',
value: 4,
},
],
isShowUserList: false,
hasClass: '',
userName: '',
}
},
methods: {
showAccountList(e) {
e.stopPropagation()
this.isShowUserList = !this.isShowUserList
if (this.isShowUserList) {
this.hasClass = '1'
} else {
this.hasClass = '0'
}
},
changeUser(data) {
console.log(data)
this.userName = data.name
this.list.map(item => {
item.selected = false
if (item.value === data.value) {
item.selected = true
}
})
this.hasClass = '0'
this.isShowUserList = false
},
hiddenSelection() {
this.hasClass = '0'
this.isShowUserList = false
},
},
})