浏览器后退/后退按钮可在选项卡之间导航


14

我收到了很多用户的抱怨,他们在使用基于jQuery的选项卡时感到很烦,当他们在浏览器上回弹时,他们没有转到上一个选项卡,而是转到了上一页。我添加了以下上一个/下一个按钮,但还不够。如何重新配置​​按钮,以便用户单击浏览器后退箭头时可以转到上一个选项卡,而不是上一个页面。您可以在这里进行测试。

$('#quicktabs-registration_steps').append('<div class="prevnext"><a class="tablink-prev btn" href="#">Prev</a><a class="tablink-next btn btn-lg btn-primary" href="#">Continue</a></div>');
$('.tablink-prev').click(function () {
    var index = $('.quicktabs-tabs li.active').index();
    $('.quicktabs-tabs li').eq(index).removeClass('active');
    if (index == 0) {
        index = 1;
    }
    $('.quicktabs-tabs li').eq(index - 1).addClass('active');
    $('.quicktabs-tabs li').eq(index - 1).find('a').click();
    return false;
});
$('.tablink-next').click(function () {
    var length = $('.quicktabs-tabs').first().children().size();;
    var index = $('.quicktabs-tabs li.active').index();
    $('.quicktabs-tabs li').eq(index).removeClass('active');
    //                if (parseInt(index) == parseInt(length) - 1 ) {
    //                    index = index - 1;
    //                }
    if (parseInt(index) == parseInt(length) - 1) {
        window.location.href = '/home'; //redirect to home
        //index = index - 1;
    }
    $('.quicktabs-tabs li').eq(index + 1).addClass('active');
    $('.quicktabs-tabs li').eq(index + 1).find('a').click();
    return false;
});

在相关的网址后面添加#tab1#tab2
Gerard

嗨,@杰拉德,您能不能举个例子。
Efe

您应注意,将来禁止使用任何浏览器来回导航可能是由于以下原因:如果存在恶意脚本,它们可以并且将控制您的浏览器,这是大型浏览器开发人员试图防止的行为。不惜一切代价。
BRO_THOM

看一看jQueryUI的标签插件:jqueryui.com/tabs。他们的文档也提供了有关键盘导航的详细信息。api.jqueryui.com/tabs。看一看。
Prasad Wargad

@Efe解决了吗?
艾比尔·侯赛因

Answers:



7

没有完整的代码,我无法为您提供定制示例,但您可以简单地将锚标记添加到每个包含div的选项卡中。

每次用户单击选项卡链接时,这都会更新URL。这些URL更改将存储在浏览器历史记录中,并在向后导航时被调出。

<div id="Tab1">
  <h2><a href="#Tab1">Tab 1</a></h2>
  <p>This tab content</p>
</div>

<div id="Tab2">
  <h2><a href="#Tab2">Tab 2</a></h2>
  <p>This tab content</p>
</div>

<div id="Tab3">
  <h2><a href="#Tab3">Tab 3</a></h2>
  <p>This tab content</p>
</div>

<div id="Tab4">
  <h2><a href="#Tab4">Tab 4</a></h2>
  <p>This tab content</p>
</div>

每次单击选项卡时,更新的URL都将如下所示:

https://example.com#Tab1

https://example.com#Tab2

https://example.com#Tab3

https://example.com#Tab4


2

一方面,您的下一个标签页功能是用JavaScript编写的,另一方面,浏览器中的后退按钮使用浏览器历史记录,因此这与您的功能无关,根本无法使您进入上一个标签页。

因此,您有两种方法可以实现它:

第一种:尝试通过刷新浏览器将步骤加载到不同的页面中,以便该页面保存在浏览器历史记录中,并按返回按钮可以看到上一步

第二:您应该有一个“上一步”按钮才能看到上一步,就像下一步按钮一样


2
实际上,有一种方法,这就是为什么浏览器中使用历史记录API的原因,它允许开发人员更新您应用中的浏览历史记录,并且通常用于SPA developer.mozilla.org/en-US/docs/Web/API/History_API
Ma 'moun othman

2

我已将bootsrap选项卡与浏览器选项卡导航一起使用,下面是完整的示例

<div class="tabs-Nav border-top-0">
    <ul class="nav" role="tablist">
        <li>
            <a
            id="friends"
            data-pagination-id="friends"
            class="active"
            data-toggle="tab"
            href="#friendsTab"
            role="tab"
            aria-controls="friends"
            aria-selected="true">
                Friends
            </a>
        </li>
        <li>
            <a id="followers" data-pagination-id="followers" class="" data-toggle="tab" href="#followersTab" role="tab" aria-controls="followers" aria-selected="false">
                Followers
            </a>
        </li>
        <li>
            <a id="followings" data-pagination-id="followings" class="" data-toggle="tab" href="#followingTab" role="tab" aria-controls="followings" aria-selected="false">
                Following
            </a>
        </li>
        <li>
            <a id="invites" data-pagination-id="invites" class="" data-toggle="tab" href="#invitesTab" role="tab" aria-controls="invites" aria-selected="false">
                Invites
            </a>
        </li>
    </ul>
</div>


/**
* add // id="friends" data-pagination-id="friends"
* in your html tabs the demo html is also added.
**/
$(document).ready(function () {
    const param = 'tabID';
    $("[data-pagination-id]").click(function () {

        const pageParam = $(this).attr('data-pagination-param') || param;

        //add tabId to the params
        addParam(pageParam, $(this).attr('data-pagination-id'), true);
    });

    const preTab = getParamVal(param);

    if (param) {
        $('[data-pagination-id="'+ preTab +'"]').click();
    }
});


 /**
 * add params to the url if preParams is false then all previous
 * params will be removed.
 **/
addParam = (pageParam, paramValue, preParams) => {
    //get current url without params
    var mainUrl = window.location.href.split('?')[0];

    //get params without url
    var paramString = location.search.substring(1);

    if (preParams && paramString) { //when params found

        //change param string to json object
        var paramsObj = JSON.parse('{"' + decodeURI(paramString).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
    } else {
        //when current params are empty then create an empty object.
        var paramsObj = {};
    }

    //only for ads tabs
    if (pageParam) {
        //add tabId to the params
        paramsObj[pageParam] = paramValue;

        //push params without refreshing the page.
        history.pushState(false, false, mainUrl + '?' + $.param(paramsObj).replace(new RegExp('%2B', 'gi'), '+'));
    }
};

 /**
 * Get value of a params from url if not exists then return null
 **/
getParamVal = (pageParam) => {
    const mainUrl = window.location.href.split('?')[0];
    const paramString = location.search.substring(1);
    const paramsObj = JSON.parse('{"' + decodeURI(paramString).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');

    return paramsObj[pageParam];
};

您可以查看我的代码的实时工作示例

1>转到https://www.notesgen.com(使用台式机)

2>创建学生帐户

3>转到我的帐户/我的下载

4>单击我的连接


1

更改散列类似于history.pushState触发popstate事件的推送状态。在浏览器上来回点击将弹出并推送这些状态,因此您不需要任何其他自定义处理程序。

PS:您可以:targetactive课堂上添加CSS样式。在window.addEventListener('popstate'这里只是日志向您展示活动,但event.state将永远是空在这种情况下。

运行代码段,尝试浏览选项卡,然后使用浏览器的后退和前进按钮。

<style type="text/css">
    div { display: none }
   :target { display: block }
</style>


  <h2><a href="#Tab1">Tab 1</a> | <a href="#Tab2">Tab 2</a> | <a href="#Tab3">Tab 3</a> | <a href="#Tab4">Tab 4</a></h2>


<div id="Tab1">
  <p>This tab 1 content</p>
</div>

<div id="Tab2">
  <p>This tab 2 content</p>
</div>

<div id="Tab3">
  <p>This tab 3 content</p>
</div>

<div id="Tab4">
  <p>This tab 4 content</p>
</div>

<script>
  (() => {
history.pushState(null, '', '#Tab1');
window.addEventListener('popstate', event => {
 console.log(window.location.hash);
});
})()
</script>


0

您需要做的第一件事是,阻止链接在click事件中通过$ event.preventDefualt()提交历史记录中的url,并使用history.pushState(data,title,url)自定义历史记录

在js中,我们有一个事件可以帮助我们控制用户的前进和后退事件。该事件名称是“ popstate”。您可以通过window.addEventListener('popstate',callback)使用它。在回调函数中,您可以激活和停用选项卡(添加和删除类)并提取网址。

我用一个示例代码展示了这一点。为了更好地进行操作和理解,请尝试在服务器或本地服务器中进行尝试,因为在此处更改url受到限制:

$('nav ul a').on('click', function($e) {
        function appendContent(hash) {
            $('#content').text(`Content of  item ${hash} `);
        }
        $e.preventDefault(); // when click the link stay in page
        let _this = this; // get the link tag
        let hash = _this.hash.replace(/\#/, '');
        
        appendContent(hash);
        $('li').removeAttr('class');
        $('a').removeAttr('class');
        $(`a[href*=${hash}]`).addClass('text-white').addClass('border-0').parent().addClass('bg-primary').addClass('last-style');
     
           history.pushState('', _this.text, hash); // add the link in history
  
        window.addEventListener('popstate', function ($e) {
             let hashAgain = location.hash.replace(/\#/, ''); // you extract the hash
            appendContent(hashAgain); // set the content of the back or forward link
          $('li').removeAttr('class');
        $('a').removeAttr('class');
        $(`a[href*=${hash}]`).addClass('text-white').addClass('border-0').parent().addClass('bg-primary').addClass('last-style'); // update the status of tab 
          
            
        });
    });
ul li {
  display: inline-block;
  margin: 1em; 
}

li a,
.last-style {
  border: 1px solid;
  padding: 0.5em 1em;
}
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" >
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Learning Java Script In Deep</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
		<script type="text/javascript" src="js/angular/angular.min.js"></script>
	</head>
	<body>
	
		<header class="text-center text-black-50">
			<h1>Learning JS in Deep</h1>
			<nav id="">
				<ul id="">
					<li><a href="#home" class="home">Home</a></li>
					<li><a href="#item1">Item 1</a></li>
					<li><a href="#item2">Item 2</a></li>
					<li><a href="#item3">Item 3</a></li>
					<li><a href="#item4">Item 4</a></li>
				</ul>
			</nav>
		</header>

        <div class="container m-auto text-center" id="content">
            <p>Load <em class="text-danger">Content</em> in Here</p>
        </div>

        <script
  src="https://code.jquery.com/jquery-3.4.1.js"
  integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
  crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
        
		
	</body>	
</html>

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.