簡體   English   中英

從導航鏈接添加和刪除活動類

[英]Add & remove active class from a navigation link

不幸的是,我一直在尋找有關如何從鏈接中添加和刪除類的教程,但沒有成功。 前面所有的問題都讓我有了一些了解,但並沒有給我想要完成的結果。

我試圖通過在單擊鏈接時添加和刪除一個類來使我的導航處於活動狀態。

就 JavaScript 而言,這是我所擁有的:

$(document).ready(function(){

    //active state  
    $(function() {
        $('li a').click(function(e) {
            e.preventDefault();
            var $this = $(this);
            $this.closest('li').children('a').removeClass('active');
            $this.parent().addClass('active');

        });
    });
});

這是我的導航:

<div id="nav">
    <div id="main-nav" class="center">
        <ul>
            <li><a href="/photography.php">Photography</a></li>
            <li><a href="/web.php">Web</a></li>
            <li><a href="/print.php">Print</a></li>

            <li class="nav-R"><a href="/about.php">About</a></li>
            <li class="nav-R"><a href="/contact.php">Contact</a></li>
        </ul>
    </div><!-- close center -->
</div><!-- close-nav -->

您正在從最近的li的子元素中刪除 'active' 類,然后將 active 類添加到當前a的父li 本着將活動類保持在錨點而不是列表項上的精神,這對您有用:

    $('li a').click(function(e) {
        e.preventDefault();
        $('a').removeClass('active');
        $(this).addClass('active');
    });

活動鏈接是活動鏈接。 在任何給定時間都不會有多個鏈接處於活動狀態,因此沒有理由對刪除active類進行具體說明。 只需從所有錨點中移除即可。

演示: http : //jsfiddle.net/rq9UB/

嘗試:

$(function() {
    $('li a').click(function(e) {
        e.preventDefault();
        var $this = $(this);
        $this.closest('ul').find('.active').removeClass('active');
        $this.parent().addClass('active');

    });
});

您的選擇器正在查看當前 ( $(this) ) a元素的父元素,然后在該元素的子元素中查找a 該元素中唯一的a是您剛剛單擊的那個。

我的解決方案改為向上移動到最近的ul ,然后找到element that currently has the class of active` element that currently has the class of元素,然后刪除該類。

此外,您發布的方法是將active類名添加到li元素,並且您希望從a元素中刪除類名。 我的方法使用li ,但可以通過簡單地從最后一行中刪除parent()來修改它以使用a

參考:

我想你想要:

$this.parents("ul").find("a").removeClass('active');

嘗試這個:

$(function() {
    $('.start').addClass('active');
        $('#main-nav a').click(function() {
        $('#main-nav a').removeClass('active');
        $(this).addClass('active');             
   });
});

只需將類 .start 添加到您希望首先使用類 .active 的導航元素。

然后在你的 css 中聲明類 .active ,如:

#main-nav a.active {

/* YOUR STYLING */

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM