【问题标题】:jQuery Textbox Cursor to end of Text?jQuery文本框光标到文本结尾?
【发布时间】:2011-08-22 15:08:07
【问题描述】:

我正在尝试使用 jQuery 在用户点击“输入”后基本上替换文本框中文本末尾的光标

我有“输入”部分工作 - 但我不知道 [在输入部分之后] - 我可以让光标返回到文本框中输入文本的末尾?

即目前,当用户按 Enter 键时 - 光标转到新行,我希望它基本上转到当前文本的末尾?

一些代码:

jQuery('#textbox').keyup(function (e) {
        if (e.keyCode == 13) {
            ... submits textbox
        }
        jQuery(this).focus(function() {
          var val = this.input.value; //store the value of the element
          this.input.value = ''; //clear the value of the element
          this.input.value = val; //set that value back.  
        )};    
});

【问题讨论】:

  • 您有链接或我们可以查看的示例吗?我的第一个猜测是某种防止违约的方法,但我不能确定。
  • 我发现了这个 - stackoverflow.com/questions/511088/… - 但不确定它是否有帮助?
  • 我的意思是你已经完成了。您的问题听起来像是您编写了一些实际代码。我们能看到那个吗?

标签: jquery textbox focus


【解决方案1】:

如果你只是想阻止'enter'键创建换行符,你可以使用preventDefault来阻止它。

$("textarea").keypress(function (event) {
    if (event.which == '13') {
        event.preventDefault();
    }
});

fiddle

如果您真的想在输入中按 anywhere 进入输入的末尾,您还可以重置将始终将光标放在输入末尾的值:

$("textarea").keypress(function (event) {
    if (event.which == '13') {
        var val = $(this).val();       
        $(this).val('');
        $(this).val(val);
        event.preventDefault();
    }
});

【讨论】:

  • 嘿,戴夫 - 非常感谢这有效:) 我认为只是 preventDefault();对我来说没问题,但也可以 +1 添加第二个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-06
  • 2015-01-03
  • 2011-11-08
  • 1970-01-01
  • 2013-12-23
相关资源
最近更新 更多