视差波涛汹涌

Parallax choppy

我的网站有基本的视差效果。但是,它非常不稳定,我不确定为什么。我的代码如下。

function parallax(){
  var $parallax = $('.parallax');
  var $scrollPos = window.scrollY;

  $parallax.css('transform', 'translateY(' + -($scrollPos * 0.3) + 'px)');
}

$window.scroll(function(){
  //Check for mobile
  if(!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ) {
    // You are in mobile browser
    requestAnimationFrame(parallax);
  }
}

您应该将用户代理检查移到滚动事件之外。现在,只要用户滚动浏览器,您就会执行数百次未编译的正则表达式。

// cache the result of the user agent test
var isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent);

$window.scroll(function(){
  if (!isMobile) {
    requestAnimationFrame(parallax);
  }
}

此外,通常建议您不要进行用户代理检查,因为它们非常脆弱;用户代理字符串可能被欺骗,新浏览器发布等。您应该使用功能检测或简单地做 CSS 设计人员对媒体查询所做的并检查屏幕宽度。如果屏幕太窄,假设您使用的是不应产生视差的小屏幕。

var parallaxEnabled = false;

// only update the variable if the browser resizes (fires when device changes orientations too)
$window.resize(function() {
    // enable parallax if greater than 720 pixels (ipad portrait)
    parallaxEnabled = document.width > 720;
});

$window.scroll(function() {
  if (parallaxEnabled) {
    requestAnimationFrame(parallax);
  }
});