如何在页面加载时基于锚标记在div之间切换?

问题描述 投票:3回答:2

我在显示定价选项的两个divs之间切换。它默认为页面加载时的第一个选项。使用锚链接,我如何才能使用切换启动选项2?

Here's the page for reference.和一个浓缩版本的Fiddle来显示我正在使用的代码。我希望“俱乐部和青年”定价在#Club-Youth锚定到URL时显示。

任何帮助是极大的赞赏!

HTML

<div class="pricing-switcher">
  <a class="toggle active" id="HS-College">High School and College</a>
  <a class="toggle" id="Club-Youth">Club and Youth</a>
</div>

<div class="pricing-wrapper">
  <div class="panels HS-College">Option 1 Option 1 Option 1 Option 1 Option 1 Option 1 Option 1 Option 1 Option 1</div>
  <div class="panels Club-Youth hide">Option 2 Option 2 Option 2 Option 2 Option 2 Option 2 Option 2 Option 2 Option 2</div>
</div>

CSS

.panels {
  display: flex;clear:both;
  padding-bottom: 30px;
}

.panels.HS-College {
  justify-content: center;
}

.panels.hide {
  display: none 
}

.pricing-switcher {
  float: left;
  width: 100%;
}

.toggle {
  float: left;
  display: flex;
  border: 2px solid #000;
  margin-right: 10px;
  cursor: pointer;
}

.toggle.active {
  background-color: red;
}

JS切换

$(document).ready(function(){
  $('.toggle').click(function(){
    var self = $(this);  
    $('.panels').addClass('hide');
    $('.toggle').removeClass('active');
    self.addClass('active');
    $('.panels.'+ self.attr('id')).removeClass('hide');
  });
});
javascript jquery css toggle anchor
2个回答
3
投票
$(window.location.hash).click();

window.location.hash将从以下网址返回#club-Youth。

https://www.hudl.com/products/assist/volleyball?token=K6~s9DTGVrSKh~X9VMetZv6YLKSMtAAp#Club-Youth

使用$(window.location.hash)将与$('#Club-Youth')相同并触发该元素上的click事件。

确保此代码低于$('。toggle')。单击(function(){})以便它触发您已附加的代码。


1
投票

在页面加载时查找URL中的哈希值

var hash = window.location.hash;
if (!(typeof object === 'undefined')) {
   // show/hide based on value of hash
   if (hash=='Club-Youth') {
      // show panel 1
   } else {
      // show panel 2
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.