本文介绍了nightwatch.js-滚动直到可见元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要滚动页面,直到所需元素显示为可见.

I want to scroll page until desired element appear visible.

我尝试过:

    browser.execute(function () {
        window.scrollBy(0, 10000000);
    }, []);

browser.getLocationInView("<selector>", function(result) {
    this.assert.equal(typeof result, "object");
    this.assert.equal(result.status, 0);
    this.assert.equal(result.value.x, 200);
    this.assert.equal(result.value.y, 200);
});

第一次不滚动页面,第二次失败,因为元素不可见.

First do not scroll page and second fails because element is not visible.

如何解决此问题?我想滚动直到元素显示为可见.

How to fix this? I want to scroll till element appear visible.

推荐答案

如果您使用的是JQuery,则可以这样做:

If you are using JQuery you can do it like this:

browser.execute(function () {
    $(window).scrollTop($('some-element').offset().top - ($(window).height() / 2));
}, []);

或使用纯JavaScript:

Or using plain JavaScript:

browser.execute(function () {
    document.getElementById("some-id").scrollIntoView();
}, []);

此外,在某些情况下,我建议使用 Nightwatch的waitForElementVisible 代替断言,因为在使用断言时,仅在给定的时间检查元素是否可见,但是使用waitForElementVisible您可以指定等待多长时间才能看到该元素.

Also, in some cases I would suggest to use Nightwatch's waitForElementVisible instead of assertions because when using assertions you only check at a given moment if the element is visible but using waitForElementVisible you can specify how long you will wait for it to be visible.

如果先前隐藏了元素,则在运行断言之前它可能不可见,这会导致断言即使该元素实际上是可见的.

If the element previously was hidden it might not be visible before the assertion is run which causes the assertion to fail even though the element is actually visible.

这篇关于nightwatch.js-滚动直到可见元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 13:29