【发布时间】:2021-10-09 11:38:25
【问题描述】:
我正在尝试设置选择下拉框的样式。自定义选择框有圆角和一个下拉列表(一个下拉选项框),显示在焦点上。我使用下面的 css 来设置选择框的样式。我还用 DIV 元素替换了 html 选择。
这是我目前使用的代码:
document.querySelector('.custom-select-wrapper').addEventListener('click', function() {
this.querySelector('.custom-select').classList.toggle('open');
for (const option of document.querySelectorAll(".custom-option")) {
option.addEventListener('click', function() {
if (!this.classList.contains('selected')) {
this.parentNode.querySelector('.custom-option.selected').classList.remove('selected');
this.classList.add('selected');
this.closest('.custom-select').querySelector('.custom-select__trigger span').textContent = this.textContent;
}
})
}
})
.custom-select-wrapper {
position: relative;
user-select: none;
width: 188px;
z-index: 30000000000;
}
.custom-select {
position: relative;
display: flex;
flex-direction: column;
}
.custom-select__trigger {
position: relative;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 10px;
height: 27px;
background: #ffffff;
cursor: pointer;
border: 1px solid #707070;
border-radius: 8px;
}
.custom-options {
position: absolute;
display: block;
top: 100%;
left: 0;
right: 0;
border: 1px solid #707070;
border-bottom-left-radius: 8px;
border-bottom-right-radius: 8px;
background: #fff;
transition: all 0.5s;
opacity: 0;
visibility: hidden;
pointer-events: none;
z-index: 2;
}
.custom-select.open .custom-options {
opacity: 1;
visibility: visible;
pointer-events: all;
}
.custom-option {
position: relative;
display: block;
padding: 0 10px 0 10px;
line-height: 25px;
cursor: pointer;
transition: all 0.5s;
}
.arrow {
position: relative;
top: 15px;
right: 15px;
}
.arrow::before,
.arrow::after {
content: "\f0d7";
font-family: "Font Awesome 5 Free";
font-size: 20px;
font-weight: 700;
color: #394a6d;
position: absolute;
bottom: 0px;
}
<div class="custom-select-wrapper">
<div class="custom-select">
<div class="custom-select__trigger">
<span>Option 1</span>
<div class="arrow"></div>
</div>
<div class="custom-options">
<span class="custom-option selected" data-value="tesla">Option 2</span>
<span class="custom-option" data-value="volvo">Option 3</span>
</div>
</div>
</div>
我应用于选择标签的样式正在生效,但问题是下拉框顶部边框与焦点上的选择框本身没有融合。是否只能将焦点上的 SELECT 输入样式从圆形边框更改为方形边框?
请在这方面有更多知识的人花几分钟时间提出解决方案吗?
【问题讨论】:
-
为什么不使用真正的
<select>标签? -
@tacoshy 因为我无法使用通常的选择框获得所需的样式
-
如果您能告诉我们您想要的确切样式,您可以。使用
<selecet>,您可以使用:focus伪选择器。 -
@tacoshy 运行代码 sn -p 可以看到想要的样式
-
是的,您可以使用 select 标签做得很好(顺便说一句。我为您包含了两次代码 sn-p)。我知道代码 sn-p...