click
點擊元素。
這會針對選取的元素發出 WebDriver click
指令,通常在未傳遞任何選項時,會捲動至選取的元素,然後點擊該元素。 當傳遞選項物件時,它會使用動作類別而不是 webdriver click,這提供了額外的功能,例如傳遞按鈕類型、座標等。 預設情況下,當使用選項時,會在執行點擊動作後傳送釋放動作指令,傳遞 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 | string 、number | 可以是 [0, "left", 1, "middle", 2, "right"] 其中之一 (選用) |
options.x 選用 | number | 數字 (選用) |
options.y 選用 | number | 數字 (選用) |
options.skipRelease 選用 | boolean | 布林值 (選用) |
範例
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
})