タブ間を移動するためのブラウザの戻る/次へボタン


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を URLの後ろに追加します
Gerard

こんにちは@Gerardさん。例を示すことはできません。
Efe

悪意のあるスクリプトがある場合、悪意のあるスクリプトがブラウザを制御できるため、大規模なブラウザ開発者が阻止しようとしている理由により、ブラウザが前後に移動できないようにすることは、将来的に非推奨になる可能性があることに注意してください。すべてのコストで。
BRO_THOM

jqueryUI Tabsプラグイン:jqueryui.com/tabsをご覧ください。また、それらのドキュメントには、キーボードナビゲーションに関する詳細も記載されています。api.jqueryui.com/tabs。見てください。
Prasad Wargad

@Efe解決しましたか?
アービルフセイン

回答:



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つの方法があります。

1つ目:ブラウザーを更新して別のページの各ステップを読み込もうとします。これにより、ページがブラウザーの履歴に保存され、戻るボタンを押すと前のステップが表示されます。

2番目:次のステップボタンと同じように前のステップを表示するには、「前へ」ボタンが必要です。


2
実際に方法があり、それがブラウザーの履歴APIである理由です。これにより、開発者はアプリの閲覧履歴を更新でき、通常はSPA developer.mozilla.org/en-US/docs/Web/API/History_API
Maで

2

以下のブラウザタブナビゲーションでブートストラップタブを使用しましたが、完全な例です

<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:クラス:targetからcssスタイルを追加できますactivewindow.addEventListener('popstate'ここだけであなたのイベントを表示するために記録しますが、event.state常にこの場合、nullになります。

コードスニペットを実行して、タブをナビゲートしてから、ブラウザーの戻るボタンと進むボタンを使用してください。

<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

最初に必要なことは、クリックイベントの$ event.preventDefualt()によって履歴内のURLを送信するリンクを防止し、history.pushState(data、title、url)で履歴をカスタマイズすることですです。

jsには、ユーザーが前後のイベントを制御するのに役立つイベントがあります。このイベント名は「popstate」です。window.addEventListener( 'popstate'、callback)で使用できます。コールバック関数では、タブ(クラスの追加と削除)をアクティブおよび非アクティブにして、URLを抽出できます。

これをサンプルコードで示します。ここで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>

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.