JS或Jquery的 - 获得滚动DIV的可视区域
-
20-09-2019 - |
题
我现在有一个是动态填充一个可滚动的div。结果 我有一个捕获UPARROW和DownArrow中文按键,并且改变父DIV中的类的功能,在某一时刻选择一个孩子 (基本上这个模拟的选择输入)
这是我想做的事: 我需要div的可视区域改变(去向上或向下),以显示最近“选择”的孩子,但只有当这个孩子是不是已经在父母的可视区域。
所以,我需要获得有关莫名其妙父div的scrollHeight属性的可视区域......但我不知道如何做到这一点...
另外,我不知道如何设置父div的可视区域。
任何帮助将不胜感激!
解决方案
卫生署,理解了它
首先,我通过
得到的可视区域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
其他提示
如果你正在使用jQuery,就可以得到元件相对于它的位置通过真实使用position()
定位的父。可滚动DIV可以设置为相对/绝对定位,使其定位。
此外,可以更改 scrollTop的属性来改变滚动位置。或jquery的scrollTop(pos)
。
您需要获得内格scrollTop的,加上外层div高度到,这将让你可视尺寸
不隶属于 StackOverflow