原生js實現select效果
阿新 • • 發佈:2018-11-15
前言
在使用select時候原生預設樣式很難修改特別是option的樣式和滑鼠經過option時候的樣式改變很難覆蓋,能力不足尚未實現,暫且記錄後續解決,現自己寫一個選擇的效果
DOM
<div class="selectBox"> <div class="select"><span class="selectText">商機</span><img src="down.png" alt=""></div> <ul class="selectOption"> <li class="selectOption1">商機</li> <li class="selectOption2">採購商</li> </ul> </div>
css
.selectBox{ width: 90px; } .select{ width: 90px; background-color: #17a6b5; height: 40px; /* position: relative; text-align: center; line-height: 40px;*/ cursor: pointer; display: flex; justify-content:center; align-items:center; border-radius: 3px; } .select img{ width: 20px; /* position: absolute; top: 10px;*/ cursor: pointer; } .selectOption{ background-color: #666666; width: 80px; list-style: none; padding-left: 0; margin-top: 0; display: none; } .selectOption li{ width: 100%; color: #ffffff; text-align: center; cursor: pointer; } .selectOption li:hover{ background-color: #17a6b5 }
JS
var selectBox = document.getElementsByClassName('selectBox')[0]; var Select = document.getElementsByClassName('select')[0]; var selectText = document.getElementsByClassName('selectText')[0]; var option = document.getElementsByClassName('selectOption')[0]; var option1 = document.getElementsByClassName('selectOption1')[0]; var option2 = document.getElementsByClassName('selectOption2')[0]; // 點選select Select.onclick = function(){ option.style.display = 'block' } // 滑鼠移除 selectBox.onmouseleave = function(){ option.style.display = 'none' } option1.onclick = function(){ option.style.display = 'none' selectText.innerHTML = '商機' } option2.onclick = function(){ option.style.display = 'none' selectText.innerHTML = '採購商' }
效果如下
樣式醜陋有待修改