2013-01-10 189 views
0

我正在查找與類'.selected'的div是否低於其容器div的底部(被overflow:hidden隱藏)。如果是,請向下滾動容器的內容以顯示下一個「頁面」,方法是滾動容器高度的等效值或滾動,直到「.selected」再次位於容器的頂部。滾動,如果div被溢出隱藏

要做到這一點,最好的方法是什麼?

+1

嘗試jQuery的網站上查找scrollTo。我爲Theakstons網站在線商店使用了類似的東西 – Pete

+0

@aaron我還沒有嘗試過任何東西,我想我會在跳入它之前詢問這裏。我發現這雖然http://stackoverflow.com/questions/5287425/overflow-hidden-jquery-selector這是一種相關 – ejfrancis

回答

2

我以前scrollTo有的來自我張貼在評論鏈接到的數學,使這個:

var top = it.position().top; 
var bd = top + it.height();  
var ch = $('.tab-demo-content').height();  
if(bd>ch){ //if focused item isn't visible, scroll to it 
    $(it).closest('.tv-container-vertical').scrollTo(it,500); //this finds its parent container and scrolls it 
} 
  • bd =距離容器的頂部所選項目的底部
  • ch =內容容器高度
1

適當的原生(非jquery)javascript代碼是:

element.scrollIntoView(); // Equivalent to element.scrollIntoView(true) 
element.scrollIntoView(alignToTop); // Boolean arguments 
element.scrollIntoView(scrollIntoViewOptions); // Object argument 

(見https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

最現代的瀏覽器都支持scrollIntoViewIfNeeded()太:

element.scrollIntoViewIfNeeded()