CSS翻滾下拉選擇框可以讓用戶方便地選擇他們需要的選項。這種選擇框也有多種不同的樣式能夠適配任何網站。
/*樣式*/ .select { position: relative; width: 18em; height: 1.8em; overflow: hidden; border: 1px solid gray; border-radius: 3px; background-color: #f2f2f2; } .option { position: absolute; top: 100%; left: 0; width: 100%; max-height: 20em; overflow-y: auto; z-index: 1; background-color: #f2f2f2; border: 1px solid gray; } .option li { padding: 0.5em 0.75em; cursor: pointer; font-size: 0.9em; color: #333; } .option li:hover { background-color: #ddd; } .arrow { position: absolute; top: 50%; right: 0.5em; margin-top: -0.25em; width: 0.5em; height: 0.5em; border: solid black; border-width: 0 1px 1px 0; transform: rotate(45deg); cursor: pointer; } .arrow.open { margin-top: -0.2em; transform: rotate(-135deg); } /*JS*/ var select = document.querySelector('.select'); var option = select.querySelector('.option'); var arrow = select.querySelector('.arrow'); /*下拉菜單開關*/ function toggle() { if (option.classList.contains('open')) { option.classList.remove('open'); arrow.classList.remove('open'); } else { option.classList.add('open'); arrow.classList.add('open'); } } /*關閉下拉菜單*/ function close(e) { var target = e.target; if (target != select && !select.contains(target)) { option.classList.remove('open'); arrow.classList.remove('open'); } } select.addEventListener('click', toggle); window.addEventListener('click', close);
HTML代碼:
<div class="select"> <span class="value">請選擇</span> <ul class="option"> <li>選項1</li> <li>選項2</li> <li>選項3</li> <li>選項4</li> </ul> <span class="arrow"></span> </div>
以上是CSS翻滾下拉選擇框的代碼解析,希望對您理解和應用CSS有所幫助。