How to set navbar item as active when user selects it?

末鹿安然 提交于 2019-12-31 22:39:14

问题


I am a new ASP.NET Web Forms developer and trying to use Twitter Bootstrap with the Master Page. I am struggling with setting navbar item as active when user selects it. I created my simple master page by following this tutorial about how to use Twitter Bootstrap with ASP.NET.

Here's the code of my master page:

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <link href="css/bootstrap.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div class="container">
            <div class="row-fluid">
                <div class="span12">
                    <div class="page-header">
                        <h1>Hello... My First Website with Twitter Bootstrap</h1>
                    </div>
                </div>
            </div>
            <div class="row-fluid">
                <div class="span3">
                    <ul class="nav nav-list">
                        <li class="nav-header">Navigation</li>
                        <li class="active"><a href="Default.aspx">ASP.NET</a></li>
                        <li><a href="Default2.aspx">Java</a></li>
                        <li><a href="#">VB.Net</a></li>
                        <li><a href="#">C#</a></li>
                    </ul> 
                </div>
                <div class="span9">
                    <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>
                </div>
            </div>
        </div>

    </div>
    </form>
</body>
</html>

Then, I added this script to the Head in order to fix issue with the menu:

<script type="text/javascript">
    $(document).ready(function () {
        var url = window.location.pathname;
        var substr = url.split('/');
        var urlaspx = substr[substr.length - 1];
        $('.nav').find('.active').removeClass('active');
        $('.nav li a').each(function () {
            if (this.href.indexOf(urlaspx) >= 0) {
                $(this).parent().addClass('active');
            }
        });
    });
</script>

However, nothing has been changed. When I selected any item from the navigation bar, the active class has not been added to the new selected item and I don't know why. Could you please help me in fixing this issue.?


回答1:


Use this:

<div class="navbar">
    <div class="navbar-inner">
        <div class="container">
            <ul class="nav">
                <li class="active"><a href="/Default.aspx">Default</a></li>
                <li><a href="/Clients.aspx">Clients</a></li>
                <li><a href="/_display/">Display</a></li>
            </ul>
        </div>
    </div>
</div>

$(document).ready(function () {
        var url = window.location;
        $('.navbar .nav').find('.active').removeClass('active');
        $('.navbar .nav li a').each(function () {
            if (this.href == url) {
                $(this).parent().addClass('active');
            }
        }); 
    });

Example: http://jsfiddle.net/yUdZx/3/

And, in the "href" use "Page.ResolveUrl"

<a href="<%= Page.ResolveUrl("~/Clients.aspx") %>">Clients</a>

It's better...




回答2:


Actually Reynaldo, almost had it... At least for me, this works pretty good, on activing the current option and deactiving the previous one, based on his example.

$(document).ready(function() {
    var url = window.location;                
    $('ul.nav li a').each(function () {
         if (this.href == url) {
              $("ul.nav li").each(function () {
                   if ($(this).hasClass("active")) {
                        $(this).removeClass("active");
                   }
              });
              $(this).parent().addClass('active');
         }
    });
});



回答3:


I've placed this in each one of my content pages, changing the id of the nav item for each page (this uses JQuery selectors). So for this to work for you you'll need to give your list items an Id. I don't add the "active" class to the master page because all we need to do is highlight the appropriate one when the content loads.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("[id$=yourNavItemId]").addClass("active");
    });
</script>

Note: if you're using ASP.NET controls instead of list items inside of your nav bar, they might be getting prefixed at runtime causing your javascript not to find the Id you think you're looking for.




回答4:


following code works if I have subpages:

 $(document).ready(function () {

        $('.navbar .nav').find('.active').removeClass('active');

        var url = window.location.toString();
        var u = url.substring(0, url.lastIndexOf("/")).toString();

        $('.navbar .nav li a').each(function () {

            var hr = this.href.substring(0, this.href.lastIndexOf('/')).toString();

            if ((u == hr) || (u.indexOf(hr) > -1))
            {
                $(this).parent().addClass('active');
                return false;
            }
        });
        // Deactivation to manually add items you have with href = "#" example:
        $('#liSalir').removeClass('active');
});



回答5:


If you are using navigation bar with dropdown-menu then put below script at end of your master page(before body closing tag):

<script type="text/javascript">
$(document).ready(function () {
    var url = window.location;
    $('ul.nav li a').each(function () {
        if (this.href == url) {
            $("ul.nav li").each(function () {
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");
                }
            });
            $(this).parent().parent().parent().addClass('active');
        }
    });
});
</script>

This completely worked for me.




回答6:


I know this post is old but use

    $(document).ready(function () {

    var url = window.location;
    $('ul.nav li a').each(function () {
        if (this.href == url) {
            $("ul.nav li").each(function () {
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");
                }
            });
            $(this).parents().addClass('active');
        }

    });

});

Since you also wants to active the all the parents.




回答7:


var windowUrl = window.location.href.toLowerCase();
//var windowUrl = window.location.href.toLowerCase().split('.')[0];
setTimeout(function () {
    var windowUrl = window.location.href.toLowerCase();
    $('#nav li').removeClass('active');
    $('#nav li').each(function (index) {
        pageUrl = $(this).find('a').attr('href');
        if (windowUrl.indexOf(pageUrl) > -1) {
            $(this).addClass('active');
        }
    });
}, 10);



回答8:


I have created a sample which full fill your requirement you need to modify the code according to your need. Use this jquery on master page

 <script type="text/javascript">
        $(function () {
            $('[id*=submenu]').addClass('sub-menu open');
            $('[id*=Master_Pages]').attr("aria-expanded", true);

            $('.subMenus').click(function () {
                localStorage.setItem('lastTab', $(this).attr('id'));
            });
        });
        function pageLoad() {
            var isActiveLink = false;
            $.each($('.subMenus'), function () {
                if ($(this).attr('id') == localStorage.getItem('lastTab')) {
                    $(this).closest('li').addClass('active');
                    localStorage.removeItem('lastTab');
                    isActiveLink = true;
                }
                else {
                    $(this).closest('li').removeClass('active');
                }
            });
            if (!isActiveLink) {
                $('[id*=Master_Designation]').closest('li').addClass('active');
            }
        }
    </script>



回答9:


For those as myself that prefer server-side implementations, transform your li tags of interest to runat="server" on the Master.Page file. The code in question will look something similar to this:

 <div class="collapse navbar-collapse" id="menu">
                <ul class="nav navbar-nav ml-auto">
                    <li class="nav-item" runat="server" id="tabHome" >
                        <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item" runat="server" id="tabContact">
                        <a class="nav-link" href="/Contact">Contact</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" runat="server">Hello, <asp:LoginName runat="server" />
                        </a>
                    </li>
                </ul>
            </div>

Then in the code behind of the Master page - Site.Master.vb or Site.Master.cs, depending on the language used - add the following in the Page Load event:

VB.Net implementation:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim thisURL As String = Request.Url.Segments(Request.Url.Segments.Count - 1)

    Select Case thisURL
        Case "Default", "default.aspx"  
            tabContact.Attributes.Remove("active")
            tabHome.Attributes.Add("class", "active")
        Case "Contact"
            tabHome.Attributes.Remove("active")
            tabContact.Attributes.Add("class", "active")
    End Select
End Sub

C# implementation:

Protected void Page_Load(Object sender, EventArgs e)
  {
    String thisURL = 
    Request.Url.Segments(Request.Url.Segments.Count - 1);

    switch (thisURL)
    {
        Case "Default":
        Case "default.aspx": 
            {
                tabContact.Attributes.Remove("active");
                tabHome.Attributes.Add("class", "active");
                break;
            }

        Case "Contact" : 
            {
                tabHome.Attributes.Remove("active");
                tabContact.Attributes.Add("class", "active");
                break;
            }
    }
}

Since is "Default.aspx" the page that is supposed to be opened initially, the "Home" menu item will be highlighted as soon the user enters the website. An example is displayed below:

For the sake of simplicity, only two navbar items were used in the example, but the same logic could be implemented if more are required.

I hope can be of help.



来源:https://stackoverflow.com/questions/17984553/how-to-set-navbar-item-as-active-when-user-selects-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!