2013-05-22 4 views
7

Я знакомясь с html5 History API, но я использую history.js расширить совместимость,История API html5, как узнать, когда пользователь щелкнул в следующих/обратных браузерах?

У меня есть один вопрос, и это то, как я могу знать:

  History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate 
       var State = History.getState(); // Note: We are using History.getState() instead of event.state 
         /* Condition here to know if this change is a back or next button, and wich one?? */ 
      }); 

Это мой «весь» код ...

var the = this; 
      var History = window.History; 
      if (!History.enabled) { 
       return false; 
      } 
      /* Store the initial content*/ 
      History.replaceState({ 
       content: $('#main').html() 
      }, document.title, document.location.href); 
      /* Bind to StateChange Event */ 
      History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate 
       var State = History.getState(); // Note: We are using History.getState() instead of event.state 
       //console.log(State); 
       //History.log(State.data, State.title, State.url); 
       console.log(history.length); 
      });   
      /* triggers */ 
      $(document).on('click','a',function(e){ 
       e.preventDefault(); 
       var href = $(this).attr('href'); 
       var title = $(this).text(); 
       if(href == '#') 
        href = title; 
       $.get('portfolio.html',function(data, response){ 
        var html = $(data).find('#main-content').html(); 
        //console.log(html); 


        $('#ajax-load').html(html); 
        History.pushState({ content: html}, title, href); 
        $('#ajax-load').css({ position:'absolute', 
              right: -$(window).width(), 
              top: the.header.height(), 
              width: $(window).width(), 
              zIndex:999 
        }).animate({ right: 0 },300,function(){ 
         console.log($('#main-content').length); 
         console.log($('#ajax-load').length); 
         $('#main-content').html(html); 
         $('#ajax-load').html(''); 
        }); 

       }); 

      }); 

Потому что единственная причина, почему я должен на самом деле проверить истории для кнопки NEXT/НАЗАД, верно? в противном случае правила якорь HREF

-EDIT-

в основном мне нужно условие отсюда

History.Adapter.bind(window,'statechange',function(){ 
       var State = History.getState(); 
       var condition = false; 
       if(condition){ 
        console.log('You clicked the next/back button'); 
       } 
}); 

Заранее спасибо

+0

Вы проверили это вопрос http://stackoverflow.com/questions/6359327/detect-back-button-click-in-browser –

+0

или это: http://stackoverflow.com/questions/16548141/is-there-a-way-to- tell-what-direction-the-state-is-going-with-history-js/16630032 # 16630032 ?? –

ответ

2

Вы можете отслеживать все состояния (ссылки) в массиве и по popstate (или statechange) сравнить новое местоположение со старым в массиве, чтобы вы знали, в каком виде пользователь заходил в историю (назад или fwd).

Или вы можете передать в state obj (первых парах для PushState) штамп времени и сравните, что старый

Вариант 1 (имеют проблемы - не использовать)

(function(){ 
    /*adding some init vars*/ 
    var the = this, arr = [], currPage; 
    var History = window.History; 
    if (!History.enabled) { 
     return false; 
    } 
    /* Store the initial content*/ 
    History.replaceState({ 
     content: $('#main').html() 
    }, document.title, document.location.href); 
    /* add to arr*/ 
    arr[arr.length] = document.location.href; 
    /*keep track of where we arein arr*/ 
    currPage = arr.length -1; 
    /* Bind to StateChange Event */ 
    History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate 
      var position, button; 
      var State = History.getState(); // Note: We are using History.getState() instead of event.state 
      //console.log(State); 
      //History.log(State.data, State.title, State.url); 
      console.log(history.length); 
      position = arr.indexOf(document.location.href); 
      button = position > currPage ? "fwd" : "back"; 
      currPage = position; 
      console.log("You pressed The "+ button + " Button"); 
     });   
     /* triggers */ 
     $(document).on('click','a',function(e){ 
      e.preventDefault(); 
      var href = $(this).attr('href'); 
      var title = $(this).text(); 
      if(href == '#') 
       href = title; 
      $.get('portfolio.html',function(data, response){ 
       var html = $(data).find('#main-content').html(); 
       //console.log(html); 


       $('#ajax-load').html(html); 
       History.pushState({ content: html}, title, href); 
       /* add to arr */ 
       arr[arr.length] = href; 
       /* keep track */ 
       currPage = arr.length -1; 
       $('#ajax-load').css({ position:'absolute', 
             right: -$(window).width(), 
             top: the.header.height(), 
             width: $(window).width(), 
             zIndex:999 
       }).animate({ right: 0 },300,function(){ 
        console.log($('#main-content').length); 
        console.log($('#ajax-load').length); 
        $('#main-content').html(html); 
        $('#ajax-load').html(''); 
       }); 

      }); 

     }); 

}()) 

Этот вариант имеет проблему, что она будет запутаться, если же ссылка будет в истории больше, чем когда-то

Вариант 2

(function(){ 
    /*adding some init vars*/ 
    var the = this, currPageTime; 
    var History = window.History; 
    if (!History.enabled) { 
     return false; 
    } 
    /* Store the initial content*/ 
    /* remember the current time */ 
    currPageTime = new Date().getTime(); 
    History.replaceState({ 
     content: $('#main').html(), 
     time : currPageTime 
    }, document.title, document.location.href); 
    /* Bind to StateChange Event */ 
    History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate 
      var pageTime, button; 
      var State = History.getState(); // Note: We are using History.getState() instead of event.state 
      //console.log(State); 
      //History.log(State.data, State.title, State.url); 
      console.log(history.length); 
      /*NOTE: I never used getState so i dont know if State.time will exist, if not change it to whatever holds the time we passed earlier */ 
      pageTime = State.time; 
      button = pageTime > currPageTime ? "fwd" : "back"; 
      currPageTime = pageTime; 
      console.log("You pressed The "+ button + " Button"); 
     });   
     /* triggers */ 
     $(document).on('click','a',function(e){ 
      e.preventDefault(); 
      var href = $(this).attr('href'); 
      var title = $(this).text(); 
      if(href == '#') 
       href = title; 
      $.get('portfolio.html',function(data, response){ 
       var html = $(data).find('#main-content').html(); 
       //console.log(html); 


       $('#ajax-load').html(html); 
       /* keep track of time */ 
       currPageTime = new Date().getTime(); 
       History.pushState({ content: html, time: currPageTime}, title, href); 
       $('#ajax-load').css({ position:'absolute', 
             right: -$(window).width(), 
             top: the.header.height(), 
             width: $(window).width(), 
             zIndex:999 
       }).animate({ right: 0 },300,function(){ 
        console.log($('#main-content').length); 
        console.log($('#ajax-load').length); 
        $('#main-content').html(html); 
        $('#ajax-load').html(''); 
       }); 

      }); 

     }); 

}()) 

PS: Я не проверял, работает ли он, если он не работает, пожалуйста, сделать скрипку и I'l попытаться исправить

1

Вам не нужно будет специально ли следующий или обратно кнопка запускается. «statechange» - это событие, которое будет срабатывать при нажатии следующей или предыдущей кнопки. Поэтому, основываясь на изменении URL-адреса, вы можете манипулировать своим html-контентом.

Кроме того, изменение состояния запускается в разных случаях, а также в разных браузерах. Chrome, например, загружает событие statechange, как только любая страница загружается, даже при обновлении, тогда как это не относится к firefox.

+0

Я действительно хочу знать, потому что я хочу рассматривать ответ по-разному в этих случаях ...;) –