如何让input文本框默认展示输入文本的末尾部分而非开头部分
实现input文本框默认展示文本末尾内容的方案
核心实现思路
- 利用input元素的
scrollLeft属性,手动设置横向滚动偏移量到最大值,即可直接展示最右侧的末尾文本,兼容性最优,不需要处理字符宽度计算问题 - 也可以通过
selectionStart、selectionEnd属性将光标定位到文本末尾,滚动位置会自动跟随光标跳转到末尾区域,适合需要同时聚焦输入框的场景
代码示例
原生JavaScript实现
// 首先获取目标input元素 const input = document.querySelector('#yourInputId'); // 无焦点场景下直接滚动到末尾 input.scrollLeft = input.scrollWidth; // 如需同时聚焦输入框,可使用光标定位方案 input.focus(); input.selectionStart = input.selectionEnd = input.value.length; // 如果需要每次输入内容后都保持展示末尾,绑定input事件即可 input.addEventListener('input', () => { input.scrollLeft = input.scrollWidth; })
Vue 适配实现
<template> <input ref="inputRef" v-model="content" @input="scrollToEnd" /> </template> <script setup> import { ref, nextTick } from 'vue' const content = ref('Starting portion, Ending Portion') const inputRef = ref(null) const scrollToEnd = async () => { // 等待DOM更新完成后再操作 await nextTick() inputRef.value.scrollLeft = inputRef.value.scrollWidth } // 页面初始化时也执行一次,保证初始值也展示末尾 scrollToEnd() </script>
React 适配实现
import { useRef, useState, useEffect } from 'react' function InputDemo() { const [content, setContent] = useState('Starting portion, Ending Portion') const inputRef = useRef(null) const scrollToEnd = () => { if(inputRef.current) { inputRef.current.scrollLeft = inputRef.current.scrollWidth } } // 初始化滚动 useEffect(() => { scrollToEnd() }, []) // 内容变化时自动滚动到末尾 useEffect(() => { scrollToEnd() }, [content]) return <input ref={inputRef} value={content} onChange={(e) => setContent(e.target.value)} /> }
注意事项
- 如果input设置了
disabled或readonly属性,focus()方案可能失效,直接使用scrollLeft赋值即可 - 框架场景下必须等待DOM异步更新完成后再执行滚动逻辑,否则会出现偏移不生效的问题
- 该方案不需要手动计算字符长度,自动适配中英文、符号等不同宽度的字符,比按字符数截取的方案兼容性更好
内容的提问来源于stack exchange,提问作者ASJ
相关产品推荐
相关产品推荐

