click
点击元素。
这会为选定的元素发出一个 WebDriver click
命令,在没有传递任何选项的情况下,通常会滚动到并点击选定的元素。当传递 options 对象时,它会使用 action 类而不是 webdriver click,这提供了额外的功能,例如传递按钮类型、坐标等。默认情况下,在使用 options 时,在执行 click 操作后会发送 release action 命令,传递 option.skipRelease=true
以跳过此操作。
注意:如果您有固定位置的元素(例如固定标题或页脚),这些元素在元素在视口中滚动后会覆盖选定的元素,则点击将在给定的坐标处发出,但会被您的固定(覆盖)元素接收。在这种情况下,会抛出以下错误
Element is not clickable at point (x, x). Other element would receive the click: ..."
要解决此问题,请尝试查找覆盖的元素并通过 execute
命令将其移除,以避免其干扰点击。您还可以尝试使用 scroll
和适合您场景的偏移量自己滚动到元素。
用法
$(selector).click({ button, x, y, skipRelease })
参数
名称 | 类型 | 详情 |
---|---|---|
options 可选 | ClickOptions | 点击选项(可选) |
options.button | 字符串 、数字 | 可以是 [0, "left", 1, "middle", 2, "right"] 中的一个(可选) |
options.x 可选 | 数字 | 数字(可选) |
options.y 可选 | 数字 | 数字(可选) |
options.skipRelease 可选 | 布尔值 | 布尔值(可选) |
示例
example.html
<button id="myButton" onclick="document.getElementById('someText').innerHTML='I was clicked'">Click me</button>
<div id="someText">I was not clicked</div>
click.js
it('should demonstrate the click command', async () => {
const myButton = await $('#myButton')
await myButton.click()
const myText = await $('#someText')
const text = await myText.getText()
assert(text === 'I was clicked') // true
})
example.js
it('should fetch menu links and visit each page', async () => {
const links = await $$('#menu a')
await links.forEach(async (link) => {
await link.click()
})
})
example.html
<button id="myButton">Click me</button>
example.js
it('should demonstrate a click using an offset', async () => {
const myButton = await $('#myButton')
await myButton.click({ x: 30 }) // clicks 30 horizontal pixels away from location of the button (from center point of element)
})
example.html
<button id="myButton">Click me</button>
example.js
it('should demonstrate a right click passed as string', async () => {
const myButton = await $('#myButton')
await myButton.click({ button: 'right' }) // opens the contextmenu at the location of the button
})
it('should demonstrate a right click passed as number while adding an offset', async () => {
const myButton = await $('#myButton')
await myButton.click({ button: 2, x: 30, y: 40 }) // opens the contextmenu 30 horizontal and 40 vertical pixels away from location of the button (from the center of element)
})
it('should skip sending releaseAction command that cause unexpected alert closure', async () => {
const myButton = await $('#myButton')
await myButton.click({ button: 2, x: 30, y: 40, skipRelease:true }) // skips sending releaseActions
})