2010-01-12 34 views
5

我目前有一個可動態填充的可滾動div。
我有抓住UPARROW和DownArrow中文按鍵,並且改變父DIV中的類有一次 (基本上這模仿的選擇輸入)js或jquery - 獲取可滾動div的可視區域

這裏選擇一個子功能就是我想做的事: 我需要div的可視區域進行更改(向下或向上)以顯示最近「選定」的孩子,但前提是該孩子尚不在父母的可視區域中。

所以我需要獲得有關莫名其妙父div的scrollHeight屬性的可視區域......但我不知道如何做到這一點...

而且,我不知道如何設置父div的可視區域。

任何幫助將不勝感激!

回答

2

衛生署,想通了

首先,我通過獲取可視區域

var viewableTop = $("#parentDiv").scrollTop; 
var viewableBottom = $("#parentDiv").innerHeight() + $("#parentDiv").scrollTop; 

因此viewableTop和viewableBottom之間的任何內容都是可見的。但是你真的不需要知道這一點。相反,你需要知道以下

//getting child position within the parent 
var childPos = $("#childDiv").position().top; 
//getting difference between the childs top and parents viewable area 
var yDiff = ($("#childDiv").position().top + $("#childDiv").outerHeight()) - $("#parentDiv").innerHeight() 

然後

//if upArrow and childPosition is above viewable area (that's why it goes negative) 
if(event.keyCode == 38 && childPos < 0) 
    $("#parentDiv").scrollTop += childPos;//add the negative number to the scrollTop 
//if downArrow and the difference between childs top and parents viewable area is greater than the height of a childDiv 
else if(event.keyCode == 40 && yDiff > $("#childDiv").outerHeight()-1) 
    $("#parentDiv").scrollTop += yDiff;//add the difference to the parents scrollTop 
0

如果您使用的是jQuery,您可以通過使用position()來獲取元素相對於其定位父級的位置。可滾動的div可以設置爲相對/絕對定位以使其定位。

此外,您可以更改scrollTop屬性以更改滾動位置。或者jquery scrollTop(pos)

+0

謝謝,是我最終想出來的我自己,做眼前這個。我張貼我自己的答案哈哈。我原本試過這個,但它沒有工作......然後在嘗試其他事情一個小時後,我回到它並讓一位同事看着它...... 他只是指出「scrollTop」是沒有拼寫「srollTop」哈哈哦,簡單的錯誤....然後,我想我的頭撞在我的辦公桌上,這樣的事情很瑣碎 – BinarySolo00100 2010-01-12 21:59:52

+0

兩組眼睛(http://c2.com/cgi/wiki?TwoSetsOfEyes)! – 2010-01-12 22:14:09

0

你需要得到內部div的scrollTop的,outter div的高度添加到這一點,這將使你的可視尺寸