2012-09-20 6 views
1

브라우저보기에 표시되는 첫 번째 요소를 얻는 방법을 알아야합니다.JQuery를 사용하여 보이는 영역에서 요소를 가져 오는 방법

저는 맞춤 스크롤러를 구현하고 있습니다. 그러나 사용자가 마우스를 사용하여 내 사용자 정의 스크롤러를 스크롤하면 엉망입니다. 스크롤 한 후 브라우저의 보이는 영역에 보이는 div를 찾아야하므로 오른쪽 요소로 스크롤 할 수 있습니다.

<div class="page"> 

    <div id="scroller" class="news-scroller"> 
     <div ><span id="up"></span></div> 
     <div ><span id="down"></span></div> 
    </div> 

    <div class="news"> 
    </div> 
    <div class="news"> 
    </div> 
    .... 
</div> 

내가 이전 또는 다음 div.news으로 스크롤 스크롤러 #up 및 #down을 사용하고 있습니다 : 여기

내 페이지의 구조입니다. (나는 scrollTo 플러그인을 사용한다.)하지만 스크롤을 위해 마우스를 사용한 후에 어떤 div.news가 페이지의 첫 번째 보이는 요소인지 이해할 필요가있다.

var current = $(".news").eq(0); 

$("#down").click(function(){ 
    if(current.next().size() > 0) 
    { 
     current = current.next(); 
     $.scrollTo("#"+current.attr("id"), 800);  

    } 
    else if(current.next().size() <= 0) 
    { 
     return 
    } 
}); 

$("#up").click(function(){ 
    if(current.prev().size() > 0) 
    { 
     current=current.prev(); 
     $.scrollTo("#"+current.attr("id"), 800); 
    } 
    else if(current.prev().size() <= 0) 
    { 
     return; 
} 
}); 

here이 예제 페이지입니다 :

는 여기 도움이 경우 내 코드입니다.

+3

을 사용할 수 있습니다 나는()은'.offset를 알아낼 것입니다. 당신의 각 항목의 top' 다음 scrollTo에게 다음에 따라 다음 오프셋 수를 브라우저 스크롤과 비교하고 방향. – Nal

+0

나는 보통 'current.next ('. news ') .css ('display ') ==='block '' 또는 가시성을 사용하여 보이는 요소들을 체크한다. 실제로'.is (: visible)'옵션이 있습니다. –

답변

2

다음 코드는 요소가 완전히 보이는지 알려줍니다.

function isElementVisisble(element) { 
      element = $(element); 
      var parent = $(window); 
     var containerLeft = parent.parent().scrollLeft(); 
     var containerRight = containerLeft + parent.parent().width(); 
     var elemLeft = element.offsetLeft; 
     var elemRight = elemLeft + $(element).width(); 
     if (elemLeft < containerLeft || elemRight > containerRight) { 
      return false; 
     } 
     return true; 
    } 

당신은

var firstVisibleElem; 
    jQuery("*").each(function(){ 
     if(isElementVisisble(this)){ 
      firstVisibleElem= this; 
       return false; 
     } 
    });