nightwatch.js - scroll until element is visible

那年仲夏 提交于 2019-12-24 07:25:57

问题


I want to scroll page until desired element appear visible.

I have tried:

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

and

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.


回答1:


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

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

Or using plain JavaScript:

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

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.



来源:https://stackoverflow.com/questions/39372354/nightwatch-js-scroll-until-element-is-visible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!