selectionStart和selectionEnd用于textarea / input在java脚本中无法正常工作

时间:2017-03-21 08:20:03

标签: javascript

我想获得光标位置的值,开始焦点结束 为此我正在使用

var doIt = function() {
    var elem = document.getElementById("mytext");
    var start = elem.selectionStart;
    var end = elem.selectionEnd;
    var selection = elem.selection;
    alert("selectionStart: " + start 
          + "\nselectionEnd :" + end
          + "\nselection: " + selection);
} 

但问题是selectionStart和selectionEnd只获得相同的最后一个值。如何正确开始和结束价值 示例是http://jsfiddle.net/5vd8pxct/,我试过

1 个答案:

答案 0 :(得分:1)

我已修改您的代码以获得所需的结果。这里boolean firstKeyup会在首次加载时和点击按钮后跟踪第一个键盘事件。

var elem = document.getElementById("mytext");
var start = 0;
var firstKeyup = true;

elem.addEventListener('keyup', function() {
  if(firstKeyup) {
    start = elem.selectionStart;
    firstKeyup = false;
  }
});

function doIt() {
  var end = elem.selectionEnd;
  var selection = elem.selection;
  alert("selectionStart: " + start 
          + "\nselectionEnd :" + end
          + "\nselection: " + selection);
  firstKeyup = true;
}
<textarea id="mytext" rows="10" cols="30">
Really long text goes here
</textarea><br/>
<button onclick="doIt();">Click Me</button>