jquery實現導航欄切換、下划線移入移出


 

這里下划線顯示使用的是偽類,用hover屬性觸發偽類,使其顯示下划線

 

代碼如下:

width: 0;
border-bottom: 2px solid blue;
-webkit-transition: width 0.5s ease-in-out;
-moz-transition: width 0.5s ease-in-out;
-ms-transition: width 0.5s ease-in-out;
-o-transition: width 0.5s ease-in-out;
transition: width 0.5s ease-in-out; /* 動畫 */

 

hover觸發偽類:

.navContent>p:hover::before{    /* hover觸發偽類 */
   width: 30px;    /* 下划線最長長度 */
}

 

完整代碼如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    </head>
    <body>
        <ul class="nav">
            <li class="navContent">
                <p>水果</p>
                <div>
                    <p>蘋果</p>
                    <p>香蕉</p>
                </div>
            </li>
            <li class="navContent">
                <p>蔬菜</p>
                <div>
                    <p>白菜</p>
                    <p>菠菜</p>
                </div>
            </li>
            <li class="navContent">
                <p>肉食</p>
                <div>
                    <p>豬肉</p>
                    <p>雞肉</p>
                </div>
            </li>
        </ul>
    </body>
</html>
<script>
$('.navContent').on('mouseenter',function(){
    $(this).siblings().find('div').css({'display':'none'});
});
$('.navContent>p').on('mouseenter',function(){
    $(this).siblings().slideDown();
    $(this).siblings().css({'display':'block'});
});
$('ul').on('mouseleave',function(){
    $('.navContent div').css({'display':'none'});    
});
$('.navContent div p').on('click',function(){   /* 添加點擊事件 */
    console.log($(this).text());
});
</script>
<style>
    ul,li{
        list-style-type: none;
    }
    .nav{
        display: flex;
        flex-direction: row;
    }
    .navContent{
        width: 100px;
        margin-right: 30px;
        position: relative;
        text-align: center;
    }
    .navContent>p::before{    /* 偽類 css2用:     css3用:: */
        content: '';      /* 偽類元素需要加content屬性 */
        position: absolute;
        bottom: 0;
        width: 0;
        border-bottom: 2px solid blue;
        -webkit-transition: width 0.5s ease-in-out;
        -moz-transition: width 0.5s ease-in-out;
        -ms-transition: width 0.5s ease-in-out;
        -o-transition: width 0.5s ease-in-out;
        transition: width 0.5s ease-in-out;
    }
    .navContent>p:hover::before{    /* hover觸發偽類 */
        width: 30px;    /* 下划線最長長度 */
    }
    .navContent>div{
        position: absolute;      /* 定位一定要注意 */
        display: none;
        background-color: #F9F9F9;
        width:100px;
    }
    .navContent div p:hover{
        color: #3ec56c;
    }
</style>

 

 

如果遇到下拉菜單無法顯示的問題,請首先檢查外層div是否設置了

overflow:hidden;

 

我就是因為這個疑惑了很久,這里標注出來,希望大家不要想我一樣踩這個純屬浪費時間的坑(我也很無奈啊)。


免責聲明!

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



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