2015-09-20 65 views
0

我有一個頁面只使用this excellent parallax function,我不想僅爲此加載jQuery。將JQuery視差翻譯爲Pure JavaScript

你可以用普通的javascript編寫這個函數,並保持它的小和可讀性? (先後在IE10 +上班,現代瀏覽器)

$(document).ready(function(){ 

    function draw() { 
     requestAnimationFrame(draw); 
     // Drawing code goes here 
     scrollEvent(); 
    } 
    draw(); 

}); 

function scrollEvent(){ 

    if(!is_touch_device()){ 
     viewportTop = $(window).scrollTop(); 
     windowHeight = $(window).height(); 
     viewportBottom = windowHeight+viewportTop; 

     if($(window).width()) 

     $('[data-parallax="true"]').each(function(){ 
      distance = viewportTop * $(this).attr('data-speed'); 
      if($(this).attr('data-direction') === 'up'){ sym = '-'; } else { sym = ''; } 
      $(this).css('transform','translate3d(0, ' + sym + distance +'px,0)'); 
     }); 

    } 
} 

function is_touch_device() { 
    return 'ontouchstart' in window // works on most browsers 
     || 'onmsgesturechange' in window; // works on ie10 
} 

回答

0

你可以做你問這裏通過看You Might Not Need jQuery什麼。

您的代碼,翻譯成JavaScript的香草,應該是這樣的:

document.addEventListener('DOMContentLoaded', function() { 
    function draw() { 
    requestAnimationFrame(draw); 
    // Drawing code goes here 
    scrollEvent(); 
    } 
    draw(); 
}); 

function scrollEvent() { 
    if (!is_touch_device()){ 
    var viewportTop = window.scrollY; 
    var windowHeight = document.documentElement.clientHeight; 
    var viewportBottom = windowHeight + viewportTop; 

    if (document.documentElement.clientWidth) { 
     var parallax = document.querySelectorAll('[data-parallax="true"]'); 
     for (var i = 0; i < parallax.length; i++) { 
     var item = parallax[i]; 
     var distance = viewportTop * item.getAttribute('data-speed'); 
     var sym = item.getAttribute('data-direction') === 'up' ? '-' : ''; 
     item.style.transform = 'translate3d(0, ' + sym + distance +'px,0)'; 
     }  
    } 
    } 
} 

function is_touch_device() { 
    return 'ontouchstart' in window || 'onmsgesturechange' in window; 
}