I am trying to check if an element has focus, in my case Input, and add a class to another element. This is what I am trying, but I am not sure why hasFocus() is not working.
onFocus () {
let isFocused = document.el.querySelector('a-input')
let focusedEl = document.el.querySelector('a-button')
if(isFocused.hasFocus()) {
focusedEl.classList.add('testClass')
}
}
I am trying to do this in a Vue.js custom directive.
There is a suggestion in the Vue.js forum to use the focusin event:
created() {
document.addEventListener('focusin', this.focusChanged)
},
beforeDestroy() {
document.removeEventListener('focusin', this.focusChanged)
},
methods: {
focusChanged (event) {
const el = event.target
// do something with the element.
}
}
Since I mentioned that I need to make it as a custom directive:
This is how I fixed it.
class someClassName {
constructor (el, config = {}) {
this.el = el
this.input = el.querySelector('.a-input')
this.button = el.querySelector('.a-button')
this.onInputFocus = this.onInputFocus.bind(this)
this.attachEvents()
}
onInputFocus () {
this.button.classList.add('testclass')
}
attachEvents () {
this.input.addEventListener('focus', this.onInputFocus)
}
}
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.