2016-10-07 2 views
0

내 웹 사이트에 기본적인 시차 효과가 있습니다. 그러나, 그것은 꽤 고르지 왜 나는 확실하지 않습니다. 내 코드는 아래와 같습니다.시차 고르지

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); 
    } 
} 
+0

답변이 도움이 되었다면 올바른 것으로 표시하십시오. – Soviut

답변

2

사용자 에이전트 검사는 스크롤 이벤트 외부로 이동해야합니다. 현재 사용자가 브라우저를 스크롤 할 때마다 컴파일되지 않은 정규 표현식을 수백 번 수행합니다.

// 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); 
    } 
} 

또한, 일반적으로 당신은 그들이 매우 깨지기 쉬운 것부터 사용자 에이전트 검사를 수행하지 DO 하는 것이 좋습니다; 사용자 에이전트 문자열은 스푸핑되거나 새로운 브라우저가 출시 될 수 있습니다. 대신 기능 감지를 사용해야하거나 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); 
    } 
});