设置下一页上的按钮以像用户

时间:2017-09-25 23:41:00

标签: javascript jquery html css

我想知道是否有人将焦点设置到用户打开的新页面上的上一页中单击的相同按钮或div。目前我的标题包含每个页面上相同的顶部导航栏,但我想要做的是当用户单击其中一个导航按钮并转到下一页时,该导航按钮保持突出显示(或焦点)在下一页。有没有办法实现这个目标?

以下是导航栏的当前代码:



div.scrollmenu {
  background-color: #333;
  overflow: auto;
  white-space: nowrap;
}

div.scrollmenu a {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px;
  text-decoration: none;
}

div.scrollmenu a:hover {
  background-color: #777;
}

div.scrollmenu a:focus {
  background-color: #777;
}

<div class="scrollmenu">
  <a tabindex="1" href="#home">Home</a>
  <a tabindex="2" href="#news">News</a>
  <a tabindex="3" href="#contact">Contact</a>
  <a tabindex="4" href="#about">About</a>
  <a tabindex="5" href="#support">Support</a>
  <a tabindex="6" href="#blog">Blog</a>
  <a tabindex="7" href="#tools">Tools</a>
  <a tabindex="8" href="#base">Base</a>
  <a tabindex="9" href="#custom">Custom</a>
  <a tabindex="10" href="#more">More</a>
  <a tabindex="11" href="#logo">Logo</a>
  <a tabindex="12" href="#friends">Friends</a>
  <a tabindex="13" href="#partners">Partners</a>
  <a tabindex="14" href="#people">People</a>
  <a tabindex="15" href="#work">Work</a>
</div>
&#13;
&#13;
&#13;

这个问题是当用户被重定向到下一页时页面会刷新页眉导航,所以如果用户点击其中一个菜单选项卡,它会在当前页面上突出显示,但随后导航到用户下一页,它不再突出显示或集中。基本上我想要它,所以当用户点击导航标签时,它会在当前页面和导航到的下一页上保持高亮显示。

使用javascript,jquery,甚至只是常规的html和css对我来说都没问题。

任何帮助总是受到赞赏

2 个答案:

答案 0 :(得分:6)

最好的方法是创建一个active类,当您切换页面时,您可以更新哪些链接应该是活动的,请查看以下示例

&#13;
&#13;
// Code goes here

$(function(){
  
  //watch for the changes in the url and update nav respectively
   $(window).hashchange(function(){
     var hash = location.hash.replace( /^#/, '' );
     alert(hash+"-"+location.hash);
     
     //update our nav now
     updateNav(location.hash);
     
   });
  
  function updateNav(hash){
    $("[data-active]").each(function (index, item){
    
    // get the active class name
      var activeClass = $(this).attr("data-active");
      //remove it from each 
      $(this).removeClass(activeClass);
       
      // get the href
      var href =$(this).attr("href");
      
      //compare and update the class if the hash is same with the href
     if(href == hash){
       $(this).addClass(activeClass); 
     }
    });
  }
  
  
  
});
&#13;
.active {
  color:red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 
 
    <nav>
      <a data-active="active"  href="#/home">Home</a>
      <a data-active="active" href="#/about">About</a>
      <a data-active="active" href="#/page2">Page 2</a>
    </nav>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-hashchange/1.3/jquery.ba-hashchange.js"></script>
    <script src="script.js"></script>
  
&#13;
&#13;
&#13;

答案 1 :(得分:1)

最常见的方法是使用Javascript / jQuery或在服务器端代码中基于URL添加类active,然后使用该类突出显示标题中的元素。

相关问题