初学js事件,想做一个点击时变红,取消聚焦时变白的div,于是我这样写代码:
<div style="width: 100px;height: 50px;border: 1px solid;"></div>
<script>
let div = document.getElementsByTagName("div")[0];
//点击时变红
div.onclick = function(){
this.style.backgroundColor = "red";
}
//取消聚焦时变白
div.onblur = function(){
this.style.backgroundColor = "white";
}
</script>
发现onclick()事件正常,但是onblur()事件无法触发。
上网查找原因是div标签默认情况下没有获得焦点focus()和失去焦点blur()两个事件。
解决方法:
给div标签加上 tabindex="-1" 属性,具有tabindex属性的标签就可以正常使用onfocus()和onblur()事件了。