问题
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