scrollIntoView vs moveToElement

前端 未结 1 1159
别跟我提以往
别跟我提以往 2020-11-28 09:55

In Selenium WebDriver, there are two major methods to put an element into a visible area:

  1. Scrolling into view:

    ((JavascriptExecutor         
    
    
            
相关标签:
1条回答
  • 2020-11-28 10:27

    scrollIntoView

    The DOM method scrollIntoView only scrolls the element into view. If scrollIntoView cannot scroll the element into view, it will just fail silently.I added an invisible element to the start of body and called scrollIntoView on it. Nothing scrolled but there was no error. Note that you have more control on how the element is scrolled with scrollIntoView than with moveToElement. Selenium is only interested in bringing the element into view so that the mouse can be placed on it. It does not give you any say in how it is going to do it. scrollIntoView however allows you, for instance, to specify whether you want the top or bottom of the element to be align with its scrollable ancestor. (See here for the details.)

    moveToElement

    The Selenium method moveToElement does two things: it scrolls the element into view and moves the mouse on top of the element. I've also tested it with elements that cannot be scrolled or moved to because they have no coordinates on screen and got no error here either.

    Choosing One

    I default to using moveToElement, with the following exceptions:

    • If you do not want to affect at all where Selenium has placed the mouse but you want to scroll something into view (a bit strange... but possible), then you should use scrollIntoView.

    • If you need to scroll an element with the kind of control that scrollIntoView gives you (like the alignment option I mentioned above), then you have to use it rather than moveToElement.

    • There are cases where trying to simulate user behavior through Selenium's commands is not possible or is very expensive to do by sending a series of Selenium commands. (Each command is a round-trip to the network. When the testing server somewhere across the Internet, it adds up.) In such cases, I use Selenium's executeScript. In such case, it can be advantageous to use scrollIntoView in the script being executed, rather then end the script, create an Action to perform the scroll, and finish the whole operation with another executeScript.

    0 讨论(0)
提交回复
热议问题