2014-11-06 65 views
1

使用这个话题: jQuery Set Cursor Position in Text Area输入的文本中设置光标使用jQuery

我写这篇文章的代码,但它不工作:

<input id="myTextInput" type="text" value="some text2"> 
<input type="button" value="set mouse" id="btn" /> 

和:

$(document).ready(function() { 
    $('#btn').on('click', function() { 
     var inp = $('#myTextInput');   
     var pos = 3; 
     inp.focus(); 
     if (inp.setSelectionRange) { 
      inp.setSelectionRange(pos, pos); 
     } else if (inp.createTextRange) { 
      var range = inp.createTextRange(); 
      range.collapse(true); 
      if (pos < 0) { 
       pos = $(this).val().length + pos; 
      } 
      range.moveEnd('character', pos); 
      range.moveStart('character', pos); 
      range.select(); 
     } 
    }); 
}); 

DEMO

我的错误在哪里? 谢谢

+0

正确的搜索词是'caret' – 2014-11-06 07:29:38

回答

2

你的错误是,你选择的jQuery对象,而不是DOM元素:replace var inp = $('#myTextInput');var inp = $('#myTextInput')[0];

JSFIDDLE


不过,我建议你使用插件从this answer,因为代码看起来更清洁:

$.fn.selectRange = function(start, end) { 
 
    return this.each(function() { 
 
    if (this.setSelectionRange) { 
 
     this.focus(); 
 
     this.setSelectionRange(start, end); 
 
    } else if (this.createTextRange) { 
 
     var range = this.createTextRange(); 
 
     range.collapse(true); 
 
     range.moveEnd('character', end); 
 
     range.moveStart('character', start); 
 
     range.select(); 
 
    } 
 
    }); 
 
}; 
 

 

 
$(document).ready(function() { 
 
    $('#btn').on('click', function() { 
 
    var pos = 7; 
 
    $('#myTextInput').focus().selectRange(pos, pos); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="myTextInput" type="text" value="some text2"> 
 
<input type="button" value="set mouse" id="btn" />

0

你需要的DOM元素,而不是使用JQuery对象setSelectionRangecreateTextRange 。 使用.get(0)来检索它。

var inp = $('#myTextInput'); 
inp.focus(); 
inp = inp.get(0); 

http://jsfiddle.net/qeanb8gk/1/

相关问题