在使用zepto進行微信網頁開發的時候,遇到一個情況,在本頁面存在四個TAB欄,每點擊一個欄會顯示相應的內容,下圖這種: 現在有一個需求是,用戶點擊了後退按鈕,需要回到上一次點擊的tab欄。 這個需求可以使用history對象進行進行處理。 首先就是history.pushState方法和histo ...
在使用zepto進行微信網頁開發的時候,遇到一個情況,在本頁面存在四個TAB欄,每點擊一個欄會顯示相應的內容,下圖這種:
現在有一個需求是,用戶點擊了後退按鈕,需要回到上一次點擊的tab欄。
這個需求可以使用history對象進行進行處理。
首先就是history.pushState方法和history.replaceState以及window的popstate對象。每次history的回退或前進,都會觸發popstate事件,所以我們就使用popstate事件做文章。
1、首先,點擊tab欄的時候,將點擊的tab欄的信息使用pushState方法在history對象中寫入一條新紀錄,比如我點擊第一個tab欄的時候,就將它的index值寫入url的hash中。
2、window上綁定popstate事件,當我點擊了後退按鈕,觸發popstate事件,此時我取出url中的hash值,它記錄著上次點擊tab欄的index信息。根據這個index信息處理tab欄的顯示與隱藏。
代碼示意:
// 添加標簽頁hash,首次進來時添加hash為p=0. if (!window.location.hash) { history.replaceState(null, null, '#p=0'); }
// 給tab欄綁定點擊事件,點擊事件處理兩件事:顯示需要顯示的內容,如果tab的index和url中的index信息不同,那麼push進入一條新的歷史記錄。 $('.navbar_item').click(function(event) { var page_idx = + (window.location.hash && window.location.hash.substr(-1)); var idx = $(this).index(); if (page_idx !== idx) { history.pushState(null, null, '#p='+idx); } $('.page_navbar').forEach(function(ele, idx2) { // 處理tab欄樣式 $(ele).find('.navbar_item').eq(idx).addClass('active').siblings('.navbar_item').removeClass('active'); }); // 顯示tab對應的內容
$('.page_navcontent').eq(idx).show().siblings('.page_navcontent').hide(); $('.page').scrollTop(0); });
// 綁定popstate事件,觸發事件後根據url中的tab的index信息進行處理 $(window).on('popstate', function(event) { var idx = + (window.location.hash && window.location.hash.substr(-1)); $('.page_navbar').eq(0).find('.navbar_item').eq(idx).trigger('click'); });
大概意思是這樣的,但是tab的index信息也不一定要放在url的hash中,也可以放在pushState的第一個參數——state對象中進行處理。