Tips on getting focus on the page

document.activeElement

Returns the currently focused element in the document, the attribute is read-only

  • Compared with the clear element, you can know whether the target element is focused
document.activeElement === document.getElementById("a")
  • When no element is in focus, point to body

element.focus()

Set target to get focus

  • For example, after entering the form page, take the initiative to make the first input focus
document.getElementById("a").focus()
  • Use the input focus feature, combined with CSS to hide the target node, and also allow the page to scroll to the specified position
#a {
    
    
	width: 0;
	height: 0;
	border: none;
	padding: 0;
	margin: 0;
	opacity: 0;
}

element.blur()

Set target out of focus

  • If you just want the target to scroll to the specified position without getting the focus, just remove the focus after the target gets the focus
document.getElementById("a").focus()
document.getElementById("a").blur()

document.hasFocus()

Check whether the document is in focus, the attribute is read-only

  • hasFocus() determines whether the page is focused, and has nothing to do with activeElement
document.hasFocus()
  • You can use this method to determine whether the user has left the page

//end

Guess you like

Origin blog.csdn.net/u013970232/article/details/111363027
Recommended