用js實現菜單的下拉列表,實用又簡單


  下拉列表本可以用<select>配合<option>來寫,方便得很。但是在前端中,好用的東西都有兼容,為了避免出現兼容性的問題,下拉列表用js寫再合適不行了。

 

<body>部分————————簡單的布個局

<body>
    <div id="box">請選擇手機名稱</div>
    <div id="down">
        <ul class="phones">
            <li>華為</li>
            <li>小米</li>
            <li>oppo</li>
            <li>vivo</li>
            <li>愛瘋</li>
            <li>三星</li>
        </ul>
    </div>
</body>

 

 

<style>部分————————再簡單也要把樣式寫好看點

<style>
        #box{
            color: aliceblue;
            width: 110px;
            height: 25px;
            border: 1px solid #c5c5c5;
            border-radius: 10px;
            background-color: #797777;
            text-align: center;
            /* text-indent: 5px; */
            font-size: 14px;
            line-height: 25px;
            cursor: pointer;
        }
        #down{
            border: 1px solid #c5c5c5;
            width: 90px;
            margin-left: 5px;
            display: none;
        }
        ul{
            padding: 0;
            margin: 0;
        }
        li{
            list-style: none;
            font-size: 14px;
            border-bottom: 1px dashed #c5c5c5;
            text-align: center;
            height: 25px;
            line-height: 25px;
            color: aliceblue;
            background-color: #333;
            cursor: pointer;
        }
        li:hover{
            background-color: #5c0e0e;
        }
    </style>

 

 

<script>部分————————實現功能的部分

<script>
        var obox = document.getElementById("box");
        var odown = document.getElementById("down");
        var oli = document.querySelectorAll("li");
        console.log(oli);
        var timer;
        //當點擊obox時,呈現出下拉列表的內容,給個延時效果
        obox.onclick = function(){
            clearInterval(timer);
            timer = setInterval(function(){
                odown.style.display = "block";
            },300)
            ///選中列表中的某一項並將其呈現在box中,隱藏下拉列表
            for(var i=0;i<oli.length;i++){
                oli[i].n = i;
                oli[i].onclick = function(){
                    obox.innerHTML = this.innerHTML;
                    odown.style.display = "none";
                    clearInterval(timer);
                }
            }
        }
</script>

  以上就是我寫的一個簡單的下拉列表,尚有欠缺處,還望包含。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM