js实现聚焦
聚焦实现方法
在JavaScript中实现聚焦通常涉及将焦点设置到特定的DOM元素上。以下是几种常见的实现方式:
使用focus()方法
最基本的聚焦方法是调用元素的focus()方法:
document.getElementById('myInput').focus();
自动聚焦页面加载
在页面加载时自动聚焦到某个元素:

window.onload = function() {
document.getElementById('myInput').focus();
};
通过tabindex设置
对于非表单元素,需要先设置tabindex属性才能聚焦:
<div id="focusableDiv" tabindex="0">可聚焦的div</div>
document.getElementById('focusableDiv').focus();
聚焦验证
在聚焦前检查元素是否存在和是否可聚焦:

const element = document.getElementById('myElement');
if(element && typeof element.focus === 'function') {
element.focus();
}
聚焦样式变化
聚焦时可以添加样式变化:
.focused {
border: 2px solid blue;
box-shadow: 0 0 5px blue;
}
const input = document.getElementById('myInput');
input.addEventListener('focus', () => {
input.classList.add('focused');
});
input.addEventListener('blur', () => {
input.classList.remove('focused');
});
聚焦事件监听
监听聚焦和失焦事件:
const element = document.getElementById('myElement');
element.addEventListener('focus', function() {
console.log('元素获得焦点');
});
element.addEventListener('blur', function() {
console.log('元素失去焦点');
});
聚焦管理
管理页面上的焦点顺序:
const focusableElements = document.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
focusableElements.forEach((el, index) => {
el.addEventListener('keydown', (e) => {
if(e.key === 'Tab') {
e.preventDefault();
const nextIndex = (index + 1) % focusableElements.length;
focusableElements[nextIndex].focus();
}
});
});
这些方法可以根据具体需求组合使用,实现各种聚焦场景的需求。






