2013-03-16 77 views
0

使用iScoll.js即時幫助在iOS上滾動動畫。基本上它使用硬件加速的CSS屬性來移動內容,而不是傳統的滾動。使用iScroll.js的iOS動畫錨點滾動方法

iScoll運行良好,但我也試圖實現平滑的滾動錨點解決方案。

它可以在桌面上正常工作,但問題是我無法制定如何檢索正確的偏移值以傳遞給iScoll實例。我覺得像IM超接近的解決方案:

var ua = navigator.userAgent, 
    isMobileWebkit = /WebKit/.test(ua) && /Mobile/.test(ua); 

if (isMobileWebkit) { 
     iScrollInstance = new iScroll('wrapper'); 
} 


$('a[href*=#]:not([href=#])').click(function() { 
     if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
      || location.hostname == this.hostname) { 
      var target = $(this.hash); 
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
       if (target.length) { 
        if (isMobileWebkit) { 
         iScrollInstance.refresh(); 
/* issue here with "target.position.top" = "undefined" */ 
         iScrollInstance.scrollTo(0, target.position.top, 1000); 
        }else{ 
         $('html,body').animate({ 
         scrollTop: target.offset().top 
         }, 1000); 
        } 
       return false; 
      } 
     } 
    }); 

充分演示這裏http://jsfiddle.net/Wccev/3/

回答

0

不知道爲什麼,但它似乎iScroll.js不喜歡的jQuery的scrollTo功能。因此提前設置變量似乎有所幫助。由於iScroll移動div而不是屏幕,我還必須計算出正確的偏移量。

如果有人需要它,這個jQuery應與iOS設備上的平滑滾動錨幫助提供您設置iScroll正確:

var ua = navigator.userAgent, 
    isMobileWebkit = /WebKit/.test(ua) && /Mobile/.test(ua); 

if (isMobileWebkit) { 
    $('html').addClass('mobile'); 
} 

$('a[href*=#]:not([href=#])').click(function() { 
     if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
      || location.hostname == this.hostname) { 
      var target = $(this.hash); 
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
       if (target.length) { 
        if (isMobileWebkit) { 
         scrollOffset = $('#scroller').position().top; 
         targetOffset = target.offset().top; 
         iScrollInstance.refresh(); 
         iScrollInstance.scrollTo(0, -(targetOffset-scrollOffset), 1000); 
        }else{ 
         $('html,body').animate({ 
         scrollTop: target.offset().top 
         }, 1000); 
        } 
       return false; 
      } 
     } 
    });