相关疑难解决方法(0)

jQuery在文本区域中设置光标位置

如何使用jQuery在文本字段中设置光标位置?我有一个包含内容的文本字段,我希望用户光标在关注字段时定位在某个偏移处.代码应该看起来像这样:

$('#input').focus(function() {
  $(this).setCursorPosition(4);
});
Run Code Online (Sandbox Code Playgroud)

setCursorPosition函数的实现是什么样的?如果您有一个内容为abcdefg的文本字段,则此调用将导致光标定位如下:abcd**|**efg.

Java有一个类似的功能,setCaretPosition.javascript是否存在类似的方法?

更新:我修改了CMS的代码以使用jQuery,如下所示:

new function($) {
  $.fn.setCursorPosition = function(pos) {
    if (this.setSelectionRange) {
      this.setSelectionRange(pos, pos);
    } else if (this.createTextRange) {
      var range = this.createTextRange();
      range.collapse(true);
      if(pos < 0) {
        pos = $(this).val().length + pos;
      }
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);
Run Code Online (Sandbox Code Playgroud)

html javascript jquery textfield

434
推荐指数
10
解决办法
33万
查看次数

在没有焦点的情况下替换textarea中的文本

我想替换所选文本(如果没有选择任何内容,则在光标位置后插入新文本).新文本从另一个文本框输入.
我希望能够插入新文本而不先在textarea中单击(聚焦).
含义:首先选择要在textarea中替换的文本,然后在文本框中输入新文本并单击按钮.

<textarea id='text' cols="40" rows="20">
</textarea>

<div id="opt">
    <input id="input" type="text" size="35">
    <input type="button" onclick='pasteIntoInput(document.getElementById("input").value)' value="button"/>    
</div>


function pasteIntoInput(text) { 
  el=document.getElementById("text");
  el.focus();    
  if (typeof el.selectionStart == "number"&& typeof el.selectionEnd == "number") { 
    var val = el.value; 
    var selStart = el.selectionStart;
    el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);        
    el.selectionEnd = el.selectionStart = selStart + text.length;
  } 
  else if (typeof document.selection != "undefined") {
    var textRange = document.selection.createRange();        
    textRange.text = text;       
    textRange.collapse(false);        
    textRange.select();
  } 
}  
Run Code Online (Sandbox Code Playgroud)

在线示例: 链接文本

html javascript textarea selection

6
推荐指数
1
解决办法
4997
查看次数

标签 统计

html ×2

javascript ×2

jquery ×1

selection ×1

textarea ×1

textfield ×1