我正在使用Bootstrap选项卡,并在第二个选项卡上设置了“active”类。刷新页面时,无论我在哪个选项卡上,该默认活动选项卡总会在显示最后一个访问选项卡之前显示一秒钟。我怎么阻止这个?
这是我的代码:
HTML
<ul class="nav nav-tabs" role="tablist">
<li><a class="cta2" href="home.html#contact">Get an offer</a></li>
<li role="presentation" class="active"><a href="#kids" role="tab" data-toggle="tab">Kids</a></li>
<li role="presentation"><a href="#documentary" aria-controls="documentary" role="tab" data-toggle="tab">Documentary</a></li>
<li role="presentation"><a href="#lifestyle" aria-controls="lifestyle" role="tab" data-toggle="tab">Lifestyle</a></li>
<li role="presentation"><a href="#news" aria-controls="news" role="tab" data-toggle="tab">News</a></li>
<li role="presentation"><a href="#fashion" aria-controls="fashion" role="tab" data-toggle="tab">Fashion</a></li>
<li role="presentation"><a href="#sports" aria-controls="sports" role="tab" data-toggle="tab">Sports</a></li>
<li role="presentation"><a href="#music" aria-controls="music" role="tab" data-toggle="tab">Music</a></li>
<li role="presentation"><a href="#adult" aria-controls="adult" role="tab" data-toggle="tab">Adult</a></li>
</ul>
JQUERY
$(function() {
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
localStorage.setItem('lastTab', $(this).attr('href'));
});
var lastTab = localStorage.getItem('lastTab');
if (lastTab) {
$('[href="' + lastTab + '"]').tab('show');
}
});
答案 0 :(得分:0)
您的jQuery代码将在文档准备好后执行,这在页面对用户可见后是非零时间。
一个简单的黑客方法是将display: none;
添加到标签列表,然后在使用localStorage
中的数据设置可见标签后显示列表。
更好的方法是将当前选项卡保存在会话变量中,并在生成HTML时将active
类设置为相应的选项卡。
将display: none;
添加到列表中
<ul class="nav nav-tabs" role="tablist" style="display: none;">
<li><a class="cta2" href="home.html#contact">Get an offer</a></li>
<li role="presentation" class="active"><a href="#kids" role="tab" data-toggle="tab">Kids</a></li>
<li role="presentation"><a href="#documentary" aria-controls="documentary" role="tab" data-toggle="tab">Documentary</a></li>
<li role="presentation"><a href="#lifestyle" aria-controls="lifestyle" role="tab" data-toggle="tab">Lifestyle</a></li>
<li role="presentation"><a href="#news" aria-controls="news" role="tab" data-toggle="tab">News</a></li>
<li role="presentation"><a href="#fashion" aria-controls="fashion" role="tab" data-toggle="tab">Fashion</a></li>
<li role="presentation"><a href="#sports" aria-controls="sports" role="tab" data-toggle="tab">Sports</a></li>
<li role="presentation"><a href="#music" aria-controls="music" role="tab" data-toggle="tab">Music</a></li>
<li role="presentation"><a href="#adult" aria-controls="adult" role="tab" data-toggle="tab">Adult</a></li>
</ul>
在您设置标签后显示列表:
$(function() {
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
localStorage.setItem('lastTab', $(this).attr('href'));
});
var lastTab = localStorage.getItem('lastTab');
if (lastTab) {
$('[href="' + lastTab + '"]').tab('show');
}
$('.nav-tabs').show();
});