如何在文本框点击事件中设置文本框中字符的第一个位置---Chrome问题

How to set first position of character in textbox in Textbox click event ---Chrome Issue

本文关键字:字符 第一个 位置 问题 ---Chrome 置文本 文本 事件      更新时间:2023-09-26

参见下面的代码 这是 HTML

 <asp:TextBox ID="txtInTime" runat="server" CssClass="TextBox" Width="60px"
    OnClick="fnFocus(this.id)" ></asp:TextBox>

这是JavaScript

   function fnFocus(id) {
   document.getElementById(id).focus();    
   }

上面的代码在所有浏览器中都希望铬...我希望文本框单击以在第一个位置聚焦文本框。在铬不出现在字符的第一位置..请帮忙...任何建议...??

您可以使用

setSelectionRange执行此操作:

function fnFocus(id) {
    var input = document.getElementById(id);
    input.focus();
    input.setSelectionRange(0, 0);
}

演示:小提琴

setSelecionRange在Chrome中对我不起作用。

试试这个X浏览器:

设置光标位置的函数,然后我们为您的文本框设置位置

$.fn.setCursorPosition = function(pos) {this.each(function(index, elem) {
if (elem.setSelectionRange) {
  elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
  var range = elem.createTextRange();
  range.collapse(true);
  range.moveEnd('character', pos);
  range.moveStart('character', pos);
  range.select();
}   });   return this; };
$('#txtInTime').setCursorPosition(0);

在你的代码中

<asp:TextBox ID="txtInTime"...... OnClick="$(this).setCursorPosition(0);"></asp:TextBox>