恐怕这不能通过一些简单的代码进行迭代,更不用说跨浏览器。
这是一个示例,如何在 IE 中完成此操作。不幸的是,其他浏览器似乎从body/html.getBoundingClientRect()
. 边距的处理方式也不同,(IE 忽略,其他人会考虑)。
getVisibilityPercent = function () {
var target = document.getElementById('target'),
height = target.offsetHeight,
parent = target.parentElement,
targetRect = target.getBoundingClientRect(),
tLim, bLim,
percent = 1;
while (parent) {
parentRect = parent.getBoundingClientRect();
tLim = Math.max(targetRect.top, parentRect.top);
bLim = Math.min(targetRect.bottom, parentRect.bottom);
percent *= (bLim - tLim) / height;
percent = (percent < 0) ? 0 : percent;
parent = parent.parentElement;
}
return +((percent * 100).toFixed(2));
};