在开发网站页面时,如果,光标每次都在文本框的文字最后更利于用户使用,接下来,济南网站建设小编就来为大家分享一个,通过编写JavaScript代码来设置这个功能的小案例,有需要的朋友可以过来参考一下。
关键代码:
<div>
<input type="text" id="txtInput" value="前端开发、网站建设、SEO优化">
<textarea id="txtArea">第一行内容
第二行内容
光标会自动落在最后</textarea>
</div>
<script>
function setCursorToEnd(ele) {
let len = ele.value.length;
ele.setSelectionRange(len, len);
ele.focus();
}
window.onload = function() {
let input = document.getElementById('txtInput');
let textarea = document.getElementById('txtArea');
setCursorToEnd(input);
setCursorToEnd(textarea);
}
</script>
评论