繁体   English   中英

将JQuery视差转换为纯JavaScript

[英]Translate JQuery Parallax to Pure JavaScript

我有一个页面仅使用此出色的视差功能,而我不想仅为加载jQuery。

您可以用普通的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
}

您可以通过查看“ 您可能不需要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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM