document.activeElement 获取焦点元素

document.activeElement

document.activeElement三大浏览器(ie、firefox、chrome)都支持,但,针对的对象不同,返回的值也不同。

IE:

document.activeElement可获得所有聚焦的元素,包括input、textarea、div等。IE只关心光标聚焦的位置,不关心聚焦元素的性质。

chrome:

document.activeElement仅对input、textarea等标准的输入文本有效;对于div等非编辑类的元素(即使开启了contentEditable),返回的值为BODY。

fireFox:

document.activeElement可获得所有聚焦的元素。包括input、textarea、div等。


转载于:https://my.oschina.net/wolfx/blog/620252

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个示例,使用 `window.document.onkeydown` 来监听键盘事件,实现上下左右键控制光标焦点的功能: ```html <template> <div> <input ref="input1" type="text" /> <input ref="input2" type="text" /> <input ref="input3" type="text" /> <input ref="input4" type="text" /> </div> </template> <script> export default { mounted() { window.document.onkeydown = (event) => { const { key } = event; switch (key) { case "ArrowUp": this.moveFocus("up"); break; case "ArrowDown": this.moveFocus("down"); break; case "ArrowLeft": this.moveFocus("left"); break; case "ArrowRight": this.moveFocus("right"); break; } }; }, methods: { moveFocus(direction) { const inputs = [ this.$refs.input1, this.$refs.input2, this.$refs.input3, this.$refs.input4, ]; const focusedElement = document.activeElement; let currentIndex = -1; if (focusedElement) { currentIndex = inputs.findIndex((input) => input === focusedElement); } let nextIndex; switch (direction) { case "up": nextIndex = currentIndex - 2; break; case "down": nextIndex = currentIndex + 2; break; case "left": nextIndex = currentIndex - 1; break; case "right": nextIndex = currentIndex + 1; break; } if (nextIndex >= 0 && nextIndex < inputs.length) { inputs[nextIndex].focus(); } }, }, }; </script> ``` 在上述示例中,我们监听了 `window.document` 对象的 `onkeydown` 事件,并根据按下的键盘按键来执行相应的操作。在 `moveFocus` 方法中,我们获取了所有的输入框元素,并根据当前焦点元素的位置和移动方向来计算下一个焦点的位置,然后调用 `focus` 方法设置焦点到对应的输入框。 请注意,具体的实现方式可能因你所使用的框架或组件库而有所不同。上述示例是基于 Vue.js 的单文件组件,你可以根据自己的项目需求进行相应的调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值