在JavaScript中,下拉选择框(Select Box)的样式可以通过CSS来进行自定义。以下是一些基础概念和相关信息:
<select>
元素:这是创建下拉选择框的基本HTML元素。<select>
元素。以下是一个简单的自定义下拉选择框的示例:
<div class="custom-select">
<select id="mySelect">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
.custom-select {
position: relative;
display: inline-block;
width: 200px;
}
.custom-select select {
display: none; /* Hide the default select */
}
.select-selected {
background-color: #ccc;
padding: 10px;
border: 1px solid #ccc;
cursor: pointer;
}
.select-items {
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.select-items div {
padding: 10px;
cursor: pointer;
}
.select-items div:hover {
background-color: #ddd;
}
document.addEventListener('DOMContentLoaded', function() {
var x, i, selElmnt, a, s, h;
x = document.getElementsByClassName("custom-select");
for (i = 0; i < x.length; i++) {
selElmnt = x[i].getElementsByTagName("select")[0];
a = document.createElement("DIV");
a.setAttribute("class", "select-selected");
a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
x[i].appendChild(a);
h = document.createElement("DIV");
h.setAttribute("class", "select-items select-hide");
for (var j = 1; j <= selElmnt.length; j++) {
s = document.createElement("DIV");
s.innerHTML = selElmnt.options[j - 1].innerHTML;
s.addEventListener("click", function() {
var y, i;
y = this.parentNode.parentNode.getElementsByTagName("select")[0];
for (i = 0; i < y.length; i++) {
if (y.options[i].innerHTML == this.innerHTML) {
y.selectedIndex = i;
break;
}
}
a.innerHTML = this.innerHTML;
closeAllSelect(this);
});
h.appendChild(s);
}
x[i].appendChild(h);
a.addEventListener("click", function(e) {
e.stopPropagation();
closeAllSelect(this);
this.nextSibling.classList.toggle("select-hide");
});
}
function closeAllSelect(elmnt) {
var x, y, i, arrNo = [];
x = document.getElementsByClassName("select-items");
y = document.getElementsByClassName("select-selected");
for (i = 0; i < y.length; i++) {
if (elmnt == y[i]) {
arrNo.push(i);
} else {
y[i].classList.remove("select-hide");
}
}
for (i = 0; i < x.length; i++) {
if (arrNo.indexOf(i)) {
x[i].classList.add("select-hide");
}
}
}
document.addEventListener("click", closeAllSelect);
});
通过以上方法,你可以创建一个自定义样式的下拉选择框,并通过JavaScript增加一些交互功能。
领取专属 10元无门槛券
手把手带您无忧上云