【问题标题】:How can I create an active tab effect in Jquery depending on the page I'm on?如何根据我所在的页面在 Jquery 中创建活动选项卡效果?
【发布时间】:2011-07-19 02:43:25
【问题描述】:

有许多教程向您展示了如何通过从 url 中获取 # 在导航栏中创建活动标签效果。

如果您链接到同一个页面,这很好,但如果您的所有链接都在不同的页面上怎么办。有没有办法使用 Jquery 来获取 url 并使选项卡处于活动状态?

以下示例为特定选项卡提供了一个“活动”类:

var tabs = $('ul.tabs');

    tabs.each(function(i) {
        //Get all tabs
        var tab = $(this).find('> li > a');
        tab.click(function(e) {

            //Get Location of tab's content
            var contentLocation = $(this).attr('href') + "Tab";

            //Let go if not a hashed one
            if(contentLocation.charAt(0)=="#") {

                e.preventDefault();

                //Make Tab Active
                tab.removeClass('active');
                $(this).addClass('active');

                //Show Tab Content & add active class
                $(contentLocation).show().addClass('active').siblings().hide().removeClass('active');

            } 
        });

如何修改它以使用指向我网站中其他页面的链接?这是html:

<ul id="nav"  class="tabs">
    <li><a href="/" title="Home" class="active">Home</a></li>   
    <li><a href="/about/" title="About us">About</a></li>
    <li><a href="/demo/" title="Demo">Demo</a></li>
    <li><a href="/where/" class="dir" title="Where">Where</a></li>
    <li><a href="/contact/" class="dir" title="Contact Us">Contact Us</a></li>
</ul>

上面的 jquery 仅适用于#tab1、#tab2 等,如何根据当前页面名称激活选项卡?抱歉,如果这有点不清楚,很难解释!

【问题讨论】:

    标签: javascript jquery css navigation


    【解决方案1】:

    在页面加载时,您可以检查“window.location”对象以了解正在显示的页面,然后将“活动”类设置为相应的链接:

    $(文档).ready(函数 () { //遍历您的链接并查看是否在 window.location.pathname 字符串中找到它们 var loc_href = window.location.pathname; $('#nav a').each(function () { if (loc_href == $(this).attr('href')) { $(this).addClass('active'); } }); });

    注意:loc == $(this).attr('href') 行查看链接的 href 值是否与 window.location.pathname 字符串完全匹配。

    【讨论】:

      【解决方案2】:
      location.href
      

      将返回当前页面的 URL,因此您可以将 if 语句更改为 -

      if (location.href.indexOf(contentLocation) != -1) {
      

      它将检查点击的href的链接是否包含在当前页面的URL中。您显然必须更改此逻辑以满足您自己的需要。

      【讨论】:

        猜你喜欢
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多