前言
div 默认是没有 blur 事件的,但是给个 tabindex=“0” 和 outline=“0” 就能有 blur 事件了,下列给 hidefocus=“true” 的原因是兼容ie浏览器
效果图 及 代码
点击黑块让它先聚焦,现在控制台是空的
点击周围的空白区域,让黑块失焦,这时控制台输出了 “失焦了”
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>div的blur事件</title>
<style>
div{
width: 100px;
height: 100px;
background: black;
color: white;
}
</style>
</head>
<body>
<div tabindex="0" outline="0" hidefocus="true"></div>
</body>
<script>
document.querySelector('div').onblur = function() {
console.log('失焦了')
}
</script>
</html>
另外
如果觉得这样的样式有点丑, 想去掉 outline 边框的话, 只需要在 css 样式中添加 outline: none; 即可