单击时链接必须处于活动状态

时间:2018-06-11 06:13:36

标签: javascript jquery html

以下是我网站导航菜单的示例代码

<div class="container-fluid">
    <div class="row">
        <nav class="col-md-2 d-none d-md-block bg-light sidebar">
            <div class="sidebar-sticky">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link active" href="user_dashboard.html">
                            <span data-feather="home"></span>
                            Dashboard <span class="sr-only">(current)</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="Devices.html">
                            <span data-feather="file"></span>
                            My Devices
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="Request.html">
                            <span data-feather="shopping-cart"></span>
                            My Requests
                        </a>
                    </li>
                </ul>
            </div>
        </nav>
    </div>
</div>

我想要做的是,当我的页面打开时,第一个链接应该是活动的。当我单击第二个链接(在这种情况下:设备)时,它应该是活动的,而前一个链接必须变为非活动状态。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$(document).ready(function() {
  $(".nav li").removeClass("active"); //this will remove the active class from  
  //previously active menu item 
  $('#home').addClass('active');
  //for demo
  //$('#demo').addClass('active');
});
&#13;
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container-fluid">
  <div class="row">
    <div class="col-md-2">
      <div class="nav-collapse">
        <ul class="nav">
          <li id="home" class="active"><a href="#">Home</a></li>
          <li><a href="#">About Us</a></li>
          <li><a href="#">Port Polio</a></li>
          <li><a href="#">Gallery</a></li>
          <li id="demo"><a href="#">Contact Us</a></li>
        </ul>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

  

下面的代码用于水平导航栏

在每个页面中添加此脚本,并根据您的页面更改括号内的数字,例如:如果您要激活第3个链接,请将其设置为li:eq(3)

索引页面的li:eq(0), 对于默认页面,其li:eq(1), 对于联系人页面,其li:eq(2)

<script>
        $(function () { $('.navbar-nav li:eq(2)').addClass('active'); });
</script>

答案 1 :(得分:1)

您检查url的路径并将其与href的{​​{1}}匹配。

nav-link