需要後端支援前端的做法是使用history介面History原理是透過hack所有連結的跳轉事件,使得跳轉不再解除安裝當前頁面而是透過ajax獲取新頁面的內容進行手動切換頁面,同時使用window.history介面進行手動切換url。使用者在返回列表頁時會觸發window.onpopstate事件,在此事件中將之前儲存下來的列表頁面重新載入,並滾動到之前儲存的相對位置。 window.onpopstate = function(event) { if ( typeof page_events === "object" ) { page_events.deactivated(); } var obj = event.state; $( "body" ).html( $( obj.content ) ); $( window ).scrollTop( obj.scroll ); init(); if ( typeof page_events === "object" ) { page_events.activated(); } } $( "a.item[href], a.gotodetail[href]" ).on( "click", function(e) { e.preventDefault(); var url = $( this ).attr( "href" ).replace( ".html", ".ajax_h5_mode.html" ); var obj = { scroll : $( window ).scrollTop(), content: $( "body" ).html(), inject : inject, }; window.history.replaceState( obj, "", window.location.href ); window.history.pushState( obj, "", $( this ).attr( "href" ) ); if ( typeof page_events === "object" ) { page_events.deactivated(); } $.ajax( { url: url, cache: false, dataType : "html", } ).then( function( response ) { $( window ).scrollTop( 0 ); $( "body" ).html( $( response ) ); if ( typeof page_events === "object" ) { page_events.activated(); } } ).fail( function() { console.log( "獲取頁面錯誤" ); } ); } );
需要後端支援前端的做法是使用history介面History原理是透過hack所有連結的跳轉事件,使得跳轉不再解除安裝當前頁面而是透過ajax獲取新頁面的內容進行手動切換頁面,同時使用window.history介面進行手動切換url。使用者在返回列表頁時會觸發window.onpopstate事件,在此事件中將之前儲存下來的列表頁面重新載入,並滾動到之前儲存的相對位置。 window.onpopstate = function(event) { if ( typeof page_events === "object" ) { page_events.deactivated(); } var obj = event.state; $( "body" ).html( $( obj.content ) ); $( window ).scrollTop( obj.scroll ); init(); if ( typeof page_events === "object" ) { page_events.activated(); } } $( "a.item[href], a.gotodetail[href]" ).on( "click", function(e) { e.preventDefault(); var url = $( this ).attr( "href" ).replace( ".html", ".ajax_h5_mode.html" ); var obj = { scroll : $( window ).scrollTop(), content: $( "body" ).html(), inject : inject, }; window.history.replaceState( obj, "", window.location.href ); window.history.pushState( obj, "", $( this ).attr( "href" ) ); if ( typeof page_events === "object" ) { page_events.deactivated(); } $.ajax( { url: url, cache: false, dataType : "html", } ).then( function( response ) { $( window ).scrollTop( 0 ); $( "body" ).html( $( response ) ); if ( typeof page_events === "object" ) { page_events.activated(); } } ).fail( function() { console.log( "獲取頁面錯誤" ); } ); } );