标签页的网址结构

时间:2019-02-06 15:37:22

标签: javascript jquery html5 css3 tabs

因为我对标签内的网址结构有疑问。如果我选择了tab-2,并且URL更改为https://example.com/#tab-2,并且选项卡3变为了https://example.com/#tab-3,依此类推。

问题是,如果我在搜索栏中输入了此https://example.com/#tab-4或其他任何内容,它总是向我显示https://example.com/#tab-1为当前状态。

但是,我想做https://example.com/#tab-4,当前显示出我tab-4被选中。如何在当前代码中实现?

$('.projects_select').click(function(){
        var tab_id = $(this).attr('data-tab');
        $('.projects_select').removeClass('current');
        $('.tab-content').removeClass('current');

        $(this).addClass('current');
        $("#"+tab_id).addClass('current');
      //  window.location.href = window.location.href+"#tab_id";
    });
.tab-content {
  display: block;    /* undo display:none          */
  height: 0;         /* height:0 is also invisible */ 
  overflow: hidden;  }

.tab-content.current {
  height: auto;      /* let the content decide it  */ }

.projects_select {
  font-weight: 400;
  letter-spacing: 1px;
  text-align: center;
  color: #333;
  padding: 17px 0;
  width: 16.66%;
  float: left;
  cursor: pointer;
  border-style: solid;
  border-width: 1px 1px 1px 0px;
  font-style: normal;
  font-weight: 700; }


.projects_select.current {
  font-weight: 500;
  position: relative;
  color: #fff;
  background: #313641; }

.projects_select.current:after {
  top: 100%;
  left: 50%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-color: transparent;
  border-top-color: #333;
  border-width: 20px;
  margin-left: -20px;
  }

.tab_Menu{
  padding: 35px 10.7% 75px;
  background: #efefef;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper tab_Menu">
   <a class="projects_select tab-link current" data-tab="tab-1" href="#tab-1"> Tab-1 </a>
   <a class="projects_select tab-link" data-tab="tab-2" href="#tab-2"> Tab-2 </a>
   <a class="projects_select tab-link" data-tab="tab-3" href="#tab-3"> Tab-3 </a>
   <a class="projects_select tab-link" data-tab="tab-4" href="#tab-4"> Tab-4 </a>
   <a class="projects_select tab-link" data-tab="tab-5" href="#tab-5"> Tab-5 </a>
</div>
    
<div class="tab-content current" id="tab-1"> Tab-1 </div>
<div class="tab-content" id="tab-2"> Tab-2 </div>
<div class="tab-content" id="tab-3"> Tab-3 </div>
<div class="tab-content" id="tab-4"> Tab-4 </div>
<div class="tab-content" id="tab-5"> Tab-5 </div>

1 个答案:

答案 0 :(得分:1)

您可以使用window.location.hash获取哈希。因此,您可以在脚本中执行以下操作:

$(document).ready(function(){
    if($('.tab-link[href=' + window.location.hash + ']')){
        $('.tab-link[href=' + window.location.hash + ']').addClass('current');
    }
    else {
        $('.tab-link[href=#tab1]').addClass('current');
    }
});

未经测试此代码。您不再需要在HTML中设置当前类。您可以在那里删除它。