【JavaScript】customize select-picker

説明

利用JS與CSS,自定義select-picker的style

  1. 用<select>跟<option>做出真選單
  2. 隱藏掉<select>(隱藏真選單)
    〔JS部分〕
  3. 讀取真選單<select>的內容,抓到後會是NodeList形式,給它轉換成陣列
  4. 換成陣列後,用mapping method,填充成<li>option內容</li>的形式
  5. 做出一個假的option wrapper / open-bar,然後把<li>們放進去

範例

引用函式庫:FontAwesome

.selector
 select
 option 台灣
 option 香港
 option 柬埔寨
 option 越南
 option 緬甸
 option 澳洲
 option 美國
 option 中國
 option 澳洲
 option 法國
 option 印尼
 option 英國
br
br
.selector
 select
 option good
 option apple
 option orange
 option red
 option beauty
 option view
 option nonono
 option yes
 option nice
.selector
 select
  display: none
 
.select-picker
 .open-bar
  width: 190px
  height: 30px
  line-height: 30px
  padding-left: 10px
  border-radius: 3px
  border: 1px solid gray
  user-select: none
  &:after
   content: "\f0d7"
   font-family: "FontAwesome"
   float: right
   margin-right: 10px
 
 .items
  max-width: 650px
  display: none
  border: 1px solid #000
  padding: 15px
  margin: 0
  position: absolute
  z-index: 999
  background-color: #fff  

 .item
  width: 120px
  display: inline-block
  height: 25px
  list-style: none
  padding: 5px 15px
 
 .items.items-show
  display: block
  display: inline-block
  
 .item.item-active
  background-color: #eee 
const selector=document.querySelectorAll(".selector");

selector.forEach(wrapper => {
 
 const RawData=wrapper.querySelector("select");
 const options=Array.from(RawData.children).map((item, n) => `<li class="item" onclick="select(${n}, this)">${item.textContent}</li>`).join("");
 
 //Create Content
 wrapper.innerHTML+=
  `<div class="select-picker">
    <div class="open-bar" onclick="showBlock(this)">${RawData.options[RawData.selectedIndex].text}</div>
     <ul class="items">
     ${options}
     </ul>
   </div>
  </div>`;

 
});


function showBlock(e){
 e.parentNode.children[1].classList.toggle("items-show");
}


function select(index, ele){
 
 const RawData=ele.closest(".selector").children[0];
 const itemActive=ele.closest(".selector").querySelectorAll(".item-active");
 
 
 if(itemActive.length>0) {
  itemActive[0].classList.remove("item-active");
 }
 RawData.selectedIndex=index;
 ele.parentNode.parentNode.children[0].textContent=RawData.options[RawData.selectedIndex].innerHTML;
 ele.parentNode.classList.remove("items-show");
 ele.classList.add("item-active");
}

Display