焦点事件
当元素获得焦点时,浏览器会触发其上的focus事件。当失去焦点时,元素会获得blur事件。
与前文讨论的事件不同,这两个事件不会传播。子元素获得或失去焦点时,不会激活父元素的处理器。
下面的示例中,文本域在拥有焦点时会显示帮助文本。
<p>Name: <input type="text" data-help="Your full name"></p><p>Age: <input type="text" data-help="Your age in years"></p><p id="help"></p><script>let help = document.querySelector("#help");let fields = document.querySelectorAll("input");for (let field of Array.from(fields)) {field.addEventListener("focus", event => {let text = event.target.getAttribute("data-help");help.textContent = text;});field.addEventListener("blur", event => {help.textContent = "";});}</script>
当用户从浏览器标签或窗口移开时,窗口对象会收到focus事件,当移动到标签或窗口上时,则收到blur事件。
