点击按钮捕获滚动事件

3

我有一个网页,在点击按钮时会发生页面内滚动到下一节。有人能提供如何捕获该滚动的建议吗?代码位于锚点标签内,href指向#以滚动到页面中的下一个部分。我不确定如何验证是否实际起作用了滚动?

2个回答

3

您可以通过使用getBoundingClientRect()相对于视口的位置来检查锚是否滚动到窗口顶部:

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();

请注意,如果锚点位于文档底部,则锚点将不在窗口顶部,而是在窗口内某个位置。因此,您还应该考虑使用更通用的解决方案来处理这种情况:
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);
}

2
在这种情况下,你可以断言/检查以下几点:
  • the current URL to point to the correct # section:

    expect(browser.getCurrentUrl()).toEqual("https://url.com/mypage#myparagraph");
    
  • check the scrollTop position of the body element (assuming it is what is scrolled - or the other scrollable container):

    var body = $("body");
    expect(body.getCssValue("scrollTop")).toEqual("someValue");  // or apply the "greater than" check
    
  • check the current active element (assuming there is an element focused once the "anchor" paragraph is becoming active)
  • solution based on your suggestion to use window.pageYOffset - compare the value before and after the click:

    browser.executeScript('return window.pageYOffset;').then(function (offsetBefore) {
        offsetBefore = parseInt(offsetBefore);
        button.click();
    
        browser.executeScript('return window.pageYOffset;').then(function (offsetAfter) { 
             offsetAfter = parseInt(offsetAfter);
             expect(offsetAfter).toBeGreaterThan(offsetBefore);
        });
    });
    

很遗憾,这些对我都不起作用。
  1. 我不能使用第一个方法,因为我的浏览器URL没有改变。它仍然保持原来的状态。
  2. 我无法检查scrollTop位置。下面的命令在我的应用程序上不起作用。我使用了下面的代码并打印了一长串命令。 var body = $("body"); var scrollposition = body.getCssValue("scrollTop"); console.log(scrollposition); .ElementFinder { browser_: ProtractorBr
  3. 点击按钮后,浏览器没有聚焦到任何元素。它只显示地图。我认为它没有聚焦。
- NewWorld
以下解决方案有效,但我不想在我的脚本中指定位置。我担心如果在不同的环境中执行脚本可能会失败。 browser.executeScript('return window.pageYOffset;').then(function(pos) { expect(pos).toBe(829)}); 如果有更好的解决方案,请告诉我。 - NewWorld
@NewWorld 哦,好的,你可以在点击之前和之后获取 pageYOffset 的值并比较这些值。希望能有所帮助。 - alecxe
谢谢。运行得非常好。 - NewWorld
2
如果链接不在窗口内,先检查pageYOffset再进行操作是行不通的。驱动程序会在单击链接之前将其滚动到视图中。因此,即使单击失败无法跳转到引用,pageYOffset也会增加。 - Florent B.
2
@FlorentB。啊,是的,滚动到视图部分阻止了这个功能的正常工作。谢谢。 - alecxe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接