最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Selenium JavaScript - scroll element into view without overlapping with header - Stack Overflow

programmeradmin4浏览0评论
webdriver.executeScript("arguments[0].scrollIntoView();", element);

This scrolls the element into view but it goes behind the header on the page.

How can I scroll element into view so that the element is right below the header instead of behind the header?

webdriver.executeScript("arguments[0].scrollIntoView();", element);

This scrolls the element into view but it goes behind the header on the page.

How can I scroll element into view so that the element is right below the header instead of behind the header?

Share Improve this question edited Oct 14, 2016 at 18:41 Heretic Monkey 12.1k7 gold badges61 silver badges131 bronze badges asked Oct 14, 2016 at 18:11 SUMSUM 1,6614 gold badges34 silver badges58 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 12

The method scrollIntoView can scroll the element at the top or at the bottom of the view with the default being at the top:

https://developer.mozilla/en/docs/Web/API/Element/scrollIntoView

So you could scroll it at the bottom instead:

webdriver.executeScript("arguments[0].scrollIntoView(false);", element);

You could also scroll it at the top and then by a 1/4th of the height of the view:

webdriver.executeScript("arguments[0].scrollIntoView(true); window.scrollBy(0, -window.innerHeight / 4);", element);

Or just below your fixed header:

webdriver.executeScript("arguments[0].scrollIntoView(true); window.scrollBy(0, -arguments[1].offsetHeight);", element, header);

If you need to focus on the specific element try the following:

JavascriptExecutor js =(JavascriptExecutor)driver;
WebElement element =(WebElement)js.executeScript("document.querySelector('#urID').focus()");
  • You need to change #urID to proper CSS locator.

Please try this "scrollIntoViewIfNeeded()". hopefully it will automatically handle the position. i am trying in Salesforce Site. it is working fine

((JavascriptExecutor) webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded();", element)

*Notes : In Mozilla it is not supported. if you will work on Chrome and Edge then it might work fine.

发布评论

评论列表(0)

  1. 暂无评论