09.CSS3实现下拉选择框

2018-04-03  本文已影响0人  Ching_Lee

支持动画效果。

 <div class="box1">
        <div class="select open">
             <p id="title">请选择</p>
             <ul id="box1ul"  >
                 <li class="active">所有选项</li>
                 <li>javascript</li>
                 <li>html</li>
                 <li>css</li>
             </ul>
         </div>
    </div>

和外部容器相关的盒子样式省略了,只看具体里面的实现

.boxes .box1 .select{
    margin-top: 10px;
    width: 80%;

}
.boxes .box1 .select p{
    width:100%;
    text-align: center;
    background-color:blanchedalmond;
    padding:10px 0 ;
}
.boxes .box1 .select ul{
    width: 100%;
    max-height: 0px;
    overflow-y: hidden;
}

.boxes .box1 .select li{

    background-color: blanchedalmond;
    padding: 10px;
    height: 1.5em;
    list-style: none;
    border: 1px white solid;
    cursor: pointer;
}



.boxes .box1 .select li:hover{
    background-color: lightblue;
}


/*给p添加一个伪元素,作为小箭头,小箭头其实是左边框和右边框旋转45度*/
.boxes .box1 .select p:after{
    display: block;
    content: '';
    width: 10px;
    height: 10px;
    border-left:2px skyblue solid;
    border-bottom:2px skyblue solid;
    transform: rotate(135deg);
    float: right;
    margin-top: 5px;
    margin-right: 10px;
}

.boxes .box1 .select .active{
    background-color: lightblue!important;
}
<!--打开效果 -->
.boxes .box1 .select.open ul{
    max-height: 400px;
    transition: all 0.3s ease-in;
}
.boxes .box1 .select.open p:after{
    transform: rotate(-45deg);
    transition: all 0.3s ease-in;
}

<!--关闭效果-->
.boxes .box1 .select.close ul{
    max-height: 0px;
    transition: all 0.3s ease-in;
}
.boxes .box1 .select.close p:after{
    transform: rotate(135deg);
    transition: all 0.3s ease-in;
}

js主要的作用就是添加class和删除class

window.onload=function () {
  let ul=document.getElementById("box1ul");

  /*为选中的li添加背景色*/
  ul.addEventListener("click",function (e) {
      let li=ul.children;
      /*首先移除所有的li中的active类*/
      for(let i=0;i<li.length;i++){
          if(li[i].classList){
              li[i].classList.remove("active");
          }
      }
      /*之后为点击的li添加active类*/
      e.target.classList.add("active");
      let title=document.getElementById("title");
      title.innerText=e.target.innerText;
  },false);

    /*为点击头部(p)添加打开关闭*/
    let p=document.getElementById("title");
    p.addEventListener("click",function () {
        let select=document.getElementsByClassName("select")[0];
        /*如果select中包括open类,那么就添加关闭类,删除open类,关闭类中实现了ul的max-height设置为0,
        以及三角的旋转角度改变*/
        if(select.classList.contains("open")){
            select.classList.add("close");
            select.classList.remove("open");
        }

        else{
            select.classList.add("open");
            select.classList.remove("close");
        }

    })
};
上一篇 下一篇

猜你喜欢

热点阅读