Chrome/Opera输入框光标移至末尾失效,Firefox正常的解决方法
解决Chrome/Opera输入框光标到末尾但文本不可见的问题
在Chrome和Opera中,仅通过setSelectionRange将光标定位到输入框末尾时,浏览器不会自动滚动显示末尾文本。可以通过以下方式修复:
修改后的代码
JavaScript
var input = document.getElementById("Search"); input.onclick = function(){ setTimeout(function () { // 先确保输入框获得焦点 input.focus(); const len = input.value.length; if (input.setSelectionRange) { input.setSelectionRange(len, len); } else { input.value = input.value; } // 强制滚动到最右侧,显示末尾文本 input.scrollLeft = input.scrollWidth; }, 0); }
HTML(保持不变)
<input type="text" id="Search" value="Hello World to everyone that have luck in their life" />
原理说明
input.focus()确保输入框处于激活状态,避免浏览器忽略后续的滚动和选区操作input.scrollLeft = input.scrollWidth直接将输入框的水平滚动条拉到最右侧,强制触发滚动显示末尾文本,解决Chrome/Opera的滚动触发问题
内容的提问来源于stack exchange,提问作者Snake Eyes
相关产品推荐
相关产品推荐

