jQuery:animate,製做平滑的下拉菜單

CSS:css

.div,ul,p{
    cursor: pointer;  //小手樣式
}
div,ul{
    width: 150px;margin: auto;
    text-align: center;
}
div{
    margin-top: 50px;
    border: 1px solid #9599A2;
    padding: 5px 0;
    border-radius: 3px;
}
ul{
    border-bottom: 1px solid aqua; //設置下拉框的底邊框顏色
    border-right: 1px solid aqua;    //設置下拉框的右邊框顏色
    border-left: 1px solid aqua;    //設置下拉框的左邊框顏色
    height: 0;    //設置高度下拉框的高度爲0,就可用anmate讓下拉狂達到平滑下拉
    display: none;
    border-radius: 0 0 3px 3px;
    padding: 0 1px;
    opacity: 0;    //設置透明度,讓透明度從0開始漸變爲1
    background-color: aliceblue;
}
p{
    padding: 5px 0;
    margin: 0;
}
p:hover{
    background-color: aqua;
    border-radius: 0 0 3px 3px;
}

 

HTML:this

<div>請選擇客車</div>
<ul>
   <p>1</p>
   <p>2</p>
   <p>3</p>
   <p>4</p>
   <p>5</p>
</ul>

 

JS/jQuery:code

$("div").click(function(){
    //一開始下拉框是隱藏的,顯得將它「顯示」出來,當前仍是透明的
    $("ul").css("display","block");
    //獲取下拉的項目欄的個數,用來計算下拉框要漸變到多長
    window.height =$(".modal-ctt p").length;
    $("ul").animate({
        height: height *25 +'px',
        opacity: 1
    },height *60); //這裏是根據下拉菜單的項目欄個數,改變漸變時間
});

$("p").click(function(){
    //獲取被點擊的項目欄的值,並放到顯示欄(DIV)中
    var value =$(this).val();
    $("div").text(value);
    //點擊完項目欄,側讓下拉框收回去,用animate讓height和opacity漸變爲0;
    $("ul").animate({
        height: 0,
        opacity: 0
    },height *60);
    //收回去後,下拉框只是變透明的,下拉框的內容仍是在的,
    //因此咱們要在下拉框收完後,將下拉框隱藏,能夠用setTimeout在漸變完成後將下拉框隱藏
    setTimeout(function(){
        $("ul").css("display","none");
    },height *60);
});
相關文章
相關標籤/搜索