2014-07-11 2 views
2

새 프로젝트 중 하나 인 경우 스크롤 할 때 일부 배경 이미지에 대해 간단한 간단한 시차 스크립트를 작성하기로 결정했습니다. 이 효율적 충분하다jQuery로 간단한 시차 효과를 효율적으로 생성

$(document).ready(function(){ 
    parallaxScroll(); 
    $(window).bind('scroll', function() { 
    parallaxScroll(); 
    }); 
}); 

function parallaxScroll() { 
    $(".parallax").each(function() { 
    if($(this).hasClass('reverse')) { 
     $(this).css("background-position","center " + (($(this).offset().top - $(window).scrollTop())/2) + "px"); 
    } else { 
     $(this).css("background-position","center " + (($(this).offset().top - $(window).scrollTop())/-2) + "px");    
    } 
    }); 
} 

내 질문은 : 이것은 내가 생각 해낸 무엇인가? 그렇지 않은 경우 더 좋은 해결책이 있습니까? .each()를 사용하면 성능에 가장 좋을지 모르겠지만 제대로 작동하는 것 같습니다. 문서로드시 함수가 실행되는 이유는 페이지를 처음 스크롤 할 때 배경 이미지가 점프하지 않기 때문입니다.

+1

http://matthew.wagerfield.com/parallax/ - 단지 선생님이 ' – Joseph

+0

기지 그 커서 위치의 효과. 나는 그럴 필요가 없다. – Devin

+0

무엇을 위해 충분히 효율적입니까? 성능 문제가 있습니까? – Jonathan

답변

0

값을 바로으로 설정하는 css 대신 animate을 사용하는 것이 좋습니다. timers/requestAnimationFrame을 사용하여 설정 값을 지연 시키므로 애니메이션이 UI를 차단하지 않고 비동기 (다른 코드와 유사 병렬로 실행 됨)인지 확인하고 애니메이션이 매끄럽도록 보장합니다.

0

이 일반 JS 솔루션입니다,하지만 당신은 정말 쉽게 jQuery를에 포트를 할 수 있습니다 :

var lastScrollY = 0; 
var backgroundImageY = 0; 
var requestAnimationFrame = window.requestAnimationFrame || 
          window.msRequestAnimationFrame || 
          window.mozRequestAnimationFrame || 
          window.webkitRequestAnimationFrame; 

window.addEventListener('load', processScrollEvent); 

function processScrollEvent() { 
    var innerHeight = window.innerHeight; 
    var scrollHeight = document.body.scrollHeight; 
    var backgroundImage = document.querySelector('#background img'); 

    lastScrollY = document.body.scrollTop; 

    var currBackgroundImageY = Math.round(((backgroundImage.scrollHeight - innerHeight)/100) * ((lastScrollY/(innerHeight - scrollHeight)) * 100)); 

    if(currBackgroundImageY != backgroundImageY) { 
     backgroundImageY = currBackgroundImageY; 
     requestAnimationFrame(processScrollAnimationFrame); 
    } 
} 

function processScrollAnimationFrame() { 
    var backgroundImage = document.querySelector('#background img'); 
    var transforms = ['transform', 'oTransform', 'msTransform', 'mozTransform', 'webkitTransform']; 

    for(var i = 0; i < transforms.length; i++) { 
     backgroundImage.style[transforms[i]] = 'translate3d(0, ' + backgroundImageY + 'px, 0)'; 
    } 
} 
+0

뭔가 빠졌어야합니다. backgroundImageY는 어디에 정의되어 있습니까? – Devin

+0

오, 물론. 그것은 단지 파일의 시작 부분에 0으로 초기화됩니다. 내 편집보기 –

+0

음, 대부분 스크롤 이벤트에 대한 바인딩이 누락되었습니다. 사실, 거의 아무 일도 일어나지 않습니다. 그렇지 않으면 매우 간단하고 효율적입니다. 감사합니다 –

관련 문제