Doh,想通了
首先,我通过可视区域
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
本文介绍了一种使用JavaScript来实现元素在父容器中精确滚动定位的方法。通过获取子元素相对于父容器的位置,结合键盘事件,实现了向上和向下箭头键控制子元素在可视区域内的平滑滚动。
989

被折叠的 条评论
为什么被折叠?



