找了一天textbox聚焦最后一个字符,居然是AI回答的!
-------原文如下:
在VB.NET中,可以使用TextBox1.Focus()
将Web TextBox控件设置为聚焦状态。然而,由于Web应用程序的特性,无法直接通过该方式将光标定位到文本的最后。
要实现这个功能,需要结合JavaScript来操作DOM元素。下面是一段示例代码,展示了如何在页面加载完成时自动将Web TextBox控件的光标移动到文本的最后:
html<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body onload="moveCursorToEnd()">
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<script type="text/javascript">
function moveCursorToEnd() {
var textBox = document.getElementById('<%= WebTextBox1.ClientID %>'); //获取Web TextBox控件的客户端ID
if (document.selection) { //IE浏览器支持
textBox.focus();
var selRange = document.selection.createRange();
selRange.moveStart("character", -textBox.value.length);
selRange.select();
} else if (textBox.setSelectionRange) { //其他主流浏览器支持
var len = textBox.value.length;
textBox.setSelectionRange(len, len);
textBox.focus();
}
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="WebTextBox1" runat="server"></asp:TextBox> <!--此处为Web TextBox控件-->
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
上述代码会在页面加载完成时调用moveCursorToEnd()
函数,并根据不同的浏览器类型选择相应的方法将光标移动到文本的最后。