我尝试使用以下代码找出某个元素在视口底部是否部分可见:
var child = document.getElementsByClassName('className')[0];
var top = child.getBoundingClientRect().top;
var bottom = child.getBoundingClientRect().bottom;
var partiallyVisibleBottom = top > 0 && bottom > window.innerHeight;
它不能正常工作。
当我滚动以使感兴趣的元素仅部分可见并且观察变量时,我看到bottom
是900而window.innerHeight
是1000。但是,由于元素的底部是被截断,我希望这是真的:bottom > window.innerHeight
。
我在做什么错了?
不确定是否相关,但是此代码在Android WebView中运行。
答案 0 :(得分:1)
该注释已被清除很多:-D使用您的新输入,可能会有帮助。在这里,我们使用一些技巧来完成任务。注意:
"span1|span2|span3"
的过滤器是必需的,因为用户可以很好地单击距实际 span 的一个像素; id
是已知的; div.container
而不是范围上(利用事件冒泡); overflow-y: scroll
仅启用垂直滚动条; div
(container
)可能是整个窗口……还是不是整个窗口!我希望这会启发您如何进行操作,我想您不能直接使用此代码,您必须从上面的列表中选择所需的内容...
document.getElementById("container").onclick = (ev) => {
var container, target, crect, trect, partial;
ev = ev || window.event;
target = ev.target || ev.srcElement;
if ("span1|span2|span3".indexOf(target.id) !== -1) // only if a known element was actually clicked!
{
container = document.getElementById("container");
crect = container.getBoundingClientRect();
trect = target.getBoundingClientRect();
partial = trect.top < crect.top || trect.bottom > crect.bottom;
document.getElementById("status").innerText =
"target: " + target.id + " partial: " + partial;
}
};
<pre id="status">STATUS</pre>
<div id="container" style="border: 1px solid #000; height: 100px; overflow-y: scroll;">
<span id="span1" style="background-color: #f00;">This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span. This is the first span.</span>
<span id="span2" style="background-color: #0f0;">This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span. This is the second span.</span>
<span id="span3" style="background-color: #00f;">This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span. This is the third span.</span>
</div>
答案 1 :(得分:0)
最终,我发现问题出在标识“子”跨度的逻辑上。原来,有几个跨区具有相同的类名(错误),这导致了此意外结果。