2013-02-20 3 views
2

DIV와 같은 요소에 클래스를 추가하고 img, h1 등에 클래스를 추가하고 싶습니다. 사용자가 스크롤 할 때 뷰포트에 들어올 때입니다.DIV가 뷰에 들어올 때 클래스 추가

요소가 뷰포트에 있는지 여부를 어떻게 계산합니까?

의사 모드 : #swing이 뷰포트에 들어간 경우 'animated bounceOutLeft'(CSS3를 사용하여 애니메이션 재생) 클래스를 추가하십시오. 애니메이션이 완료되면 클래스 '애니메이션 bounceOutLeft'를 제거하십시오.

덕분에 내가하려고 해요 @Bibhas에

$('#star').addClass('animated bounceOutLeft'); 

PROGRESS 편집 :

난 그냥 내가 원하는 클래스를 추가하는 코드를 아는 것보다 다른 시작 위치를 모르는 이 OnScreen plugin을 구현하십시오. 개발자 도구에 클래스 이름이 있다고 나와 있기 때문에 수행 한 것 같습니다.하지만이 클래스 이름은 재생되지 않는 css3 전환입니다. 문제가 될 수있는 부분은 무엇입니까 ??

$(function() { 
    setInterval(function() { 
    $("#star")        // get all <h2>s 
     .filter(":onScreen")    // get only <h2>s on screen 
     .addClass('animated bounceOutLeft'); 
    }, 1000)        // repeat every second 
}) 
+0

http://www.whathaveyoutried.com –

+0

@ egr103 여기에서 사용법을 확인하십시오 - https://github.com/benpickles/onScreen. 'setInterval' 안에 넣어야합니다. –

+0

@Bibhas 감사합니다. DevTools에 따라 클래스 이름이 추가되었지만 내 애니메이션이 재생되지 않는 것 같습니다. 왜 이것이 사실일까요? 코드/질문이 업데이트되었습니다. – egr103

답변

6

분명히 누군가가 jQuery 플러그인을 작성했습니다. 그의 코드에서 -

function isOnScreena(elem) { 
    var $window = $(window) 
    var viewport_top = $window.scrollTop() 
    var viewport_height = $window.height() 
    var viewport_bottom = viewport_top + viewport_height 
    var $elem = $(elem) 
    var top = $elem.offset().top 
    var height = $elem.height() 
    var bottom = top + height 

    return (top >= viewport_top && top < viewport_bottom) || 
      (bottom > viewport_top && bottom <= viewport_bottom) || 
      (height > viewport_height && top <= viewport_top && bottom >= viewport_bottom) 
} 

소스 코드는 거의 20 줄입니다. 당신은 읽고 배울 수 있습니다. - https://github.com/benpickles/onScreen

+1

이것은 답이 아닌 주석으로 더 적합합니다. –

+1

그 이유를 설명해주십시오. –

+0

OP는 코딩 솔루션을 요구했기 때문에 플러그인이 아닙니다. 그래서 코딩 질문에 답하고 답을 구합니다. OP가 물었던 질문을보세요. "어떻게 ...?" –

0

getBoundingClientRect() 기능이 여기에 도움이 될 수 있습니다. Here's a CodePen I did :

$(window).on('load resize scroll',function(e){ 
    $('h2').each(function(index) { 
     var h2Height = parseInt($(this)[0].getBoundingClientRect().height); 
     var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); 
     // This will return true as soon as the heading crosses the bottom of the viewport 
     if ($(this)[0].getBoundingClientRect().top < (viewHeight - h2Height)) { 
      $('h2').eq(index).addClass('added-class'); 
     } 
    }); 
}); 

편집 :이 브라우저가 표준 모드에서 실행되고 있다고 가정 참고.

Edit2가 : @brandnewjames에서 제안 다음은, 난 그냥 스크롤의 외부 행동에 대한 또한 계정 것이다 on()에 다른 이벤트 핸들러를 추가했습니다.

관련 문제