呵呵,想通了
首先,我通过以下方式获得可视区域
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