js dom focus() blur() onfocus onblur - Kaiqisan

js dom focus() blur() onfocus onblur

Yahharoo, Kaiqisan Suu, one ordinary student programmer, now heavenly open open white, deficiency, direct entry subject.

focus(): Get focus for elements that support focus (button / input / select / a /area/ textarea/frame/option) or set elements contenteditable = "true"that do not support focus (PS: Use this with caution, once used, you can visualize the current html Element content and location, a messy operation will easily make your HTML code structure chaotic, you can use it in special circumstances)

If the current page has no focused element, the body tag is the current focused element

If you want to know which elements on the current page are focusable, you can click the tab key to confirm them one by one. After the element is focused, a new style will appear. The default is to produce a blue outer layer of the element.

/

If you don’t like the current default focus style, you can also set it yourself

input:focus {
    
    
	outline: 0;
}

After this setting, there will be no style changes when the element is focused. Then you can also DIY other styles by yourself

blur(): If the current element is in focus, cancel its focus state.

Reference Code

<button class="btn">click</button>
<input type="text" class="input" contenteditable="false"/>
let a = document.getElementsByClassName('btn')[0]
let b = document.getElementsByClassName('input')[0]
a.onclick = () => {
    
    
    b.focus()
    setTimeout(() => {
    
    
        b.blur()
    }, 1000)
}

onfocus: Register a listener event. Check the current element, if it enters the focus state, then execute the method inside

<input type="text" class="input" contenteditable="false"/>
let a = document.getElementsByClassName('input')[0]
a.onfocus = () => {
    
    
    console.count()
}

Then, every time you click on the input box and try to enter content, something new will pop up in the console bar.

a.addEventListener('focus', () => {
    
    
    console.count()
}) // 这样也可以

blur: The method and principle are the same as above

to sum up

This function is mostly used for input boxes and submission of information. It can be applied to barrier-free design on the global page . This function is for users who do not have a mouse but a keyboard. Even if the user does not have a mouse, only the tab button focuses on the element instead Scroll wheel, so that you can read the entire webpage smoothly afterwards.

Guess you like

Origin blog.csdn.net/qq_33933205/article/details/108222347