You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中输入框获焦后光标不闪烁问题求助

问题解决:下拉选择后输入框获焦但光标不闪烁

问题根源

这是浏览器默认行为导致的:当在<select>中选择选项时,浏览器会在change事件触发后继续执行下拉框的焦点相关处理逻辑,此时直接调用input.focus()虽能让输入框获得焦点状态,但浏览器后续操作会干扰光标渲染,导致光标不显示(但实际可正常输入)。而按钮点击时不存在这个浏览器内置的焦点竞争流程,因此表现正常。

解决方案

将focus()调用延迟到浏览器完成<select>的所有默认处理之后,比如用setTimeout(哪怕延迟0毫秒,也能把任务推入下一个事件循环),或者requestAnimationFrame:

修改后的代码

<template>
    <select name="list" v-model="listModel">
        <option value="Item1">Item 1</option>
        <option value="Item2">Item 2</option>
        <option value="Item3">Item 3</option>
    </select>

    <input type="text" ref="inputRef" />

    <button @click="focusOnInput">Click</button>
</template>
  
<script setup>
import { ref, watch } from 'vue'

const listModel = ref('')
const inputRef = ref('')

watch(listModel, (newVal) => {
    console.log(newVal)
    // 用setTimeout延迟执行focus,避开浏览器的select默认处理流程
    setTimeout(() => {
        inputRef.value.focus();
    }, 0)
})

function focusOnInput() {
    inputRef.value.focus();
}
</script>

另一种方案(使用requestAnimationFrame)

如果觉得setTimeout不够优雅,也可以用requestAnimationFrame,它会在浏览器下一次重绘前执行:

watch(listModel, (newVal) => {
    console.log(newVal)
    requestAnimationFrame(() => {
        inputRef.value.focus();
    })
})

验证效果

修改后,选择下拉选项时,输入框不仅能获得焦点,光标也会正常闪烁,和点击按钮的效果一致。

内容的提问来源于stack exchange,提问作者Joseph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 07:52:45