问题
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