Is there a way to programmatically trigger the TAB key to move the focus to the next focusable element? [duplicate]

百般思念 提交于 2021-01-27 02:55:06

问题


I am writing a unit test to test the tab order on my webpage and I could not find a way to simulate the user's keying down of the TAB key to focus on the next focusable element, though this seems to be an easy task.

jQuery is allowed while pure javascript solution is preferred. Any kind of help is appreciated.

// TODO
function triggerTab () {


}

$("#btn-save").focus();
triggerTab();

// Expect the focus is on the cancel button now.
console.log(document.activeElement.id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p> some text </p> 
<button id="btn-save"> save </button>
<button id="btn-cancel> cancel </button>

P.S. It is no acceptable to call focus() on the next focusable element, even if you can write code to figure out the next focusable element. So this path is NOT what I want:

function getAllFocusables () {
    ...
}

var focusables = getAllFocusables(),
    index = focusables.indexOf(document.activeElement);

$(focusables[index+1]).focus();

回答1:


You can not simulate a tab key from a standard browser using Javascript.

If you are doing your unit test using a headless browser, like phantomjs for instance, you can emulate the tab key

var webPage = require('webpage');
var page = webPage.create();

page.sendEvent('keypress', page.event.key.Tab);


来源:https://stackoverflow.com/questions/40454754/is-there-a-way-to-programmatically-trigger-the-tab-key-to-move-the-focus-to-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!