简体   繁体   中英

Is there any way in JavaScript to focus the document (content area)?

Is there any way to set focus to the document, ie the content area, in JavaScript? document.focus() doesn't seem to do anything.

In HTML 4.01 , focus is only discussed in the context of elements such as form controls and links. In HTML 5 , it is discussed much more widely. However, how focus works for documents is mostly browser dependent.

You might try:

// Give the document focus
window.focus();

// Remove focus from any focused element
if (document.activeElement) {
    document.activeElement.blur();
}

It is very well supported as well.

似乎以下代码有效......

document.activeElement.blur();

Typescript-friendly answer:

(document.activeElement as HTMLElement).blur();

Reference: https://github.com/Microsoft/TypeScript/issues/5901#issuecomment-396497729

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM