我有一个网页,点击一个按钮就会滚动到网页的下一部分。有人可以建议如何捕获该卷轴吗?代码在 anchor 标记中,href 指向 # 以滚动到页面中的下一部分。我不确定如何验证滚动是否真的有效?
最佳答案
您可以通过使用 getBoundingClientRect()
检查相对于视口(viewport)的位置来检查 anchor 是否在窗口顶部滚动:
browser.get('https://www.w3.org/TR/webdriver');
$("[href='#capabilities']").click();
// assert that the position of the anchor relative to the top border of the window is less than 16 pixels.
var anchor = $('#h-capabilities');
var isCloseToTop = browser.executeScript(e => !(e.getBoundingClientRect().top >> 4), anchor);
expect(isCloseToTop).toBeTruthy();
请注意,如果 anchor 位于文档的最底部,则 anchor 不会位于窗口的顶部,而是位于其中的某个位置。 因此,您还应该使用更通用的解决方案来考虑这种情况:
browser.get('https://www.w3.org/TR/webdriver');
$("[href='#informative-references']").click();
expect(isScrolledTop($('#h-informative-references'))).toBeTruthy();
function isScrolledTop(element) {
return browser.executeScript(function(elem) {
var doc = elem.ownerDocument,
viewHeight = doc.defaultView.innerHeight,
docBottom = doc.documentElement.getBoundingClientRect().bottom,
box = elem.getBoundingClientRect();
return box.top > -1 && (box.top < 25 || (docBottom - viewHeight) < 25);
}, element);
}
关于javascript - 单击按钮捕获滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39967543/