Get caret position in contentEditable div

2018-12-31 15:33发布

I'm finding tons of good, crossbrowser anwers on how to SET the cursor or caret position in a contentEditable DIV, but none on how to GET or find its position...

What I want to do is know the position of the caret within this div, on keyup.

So, when the user is typing text, I can at any point know its cursor's position within the div.

EDIT: I'm looking for the INDEX within the div contents (text), not the cursor coordinates.

<div id="contentBox" contentEditable="true"></div>

$('#contentbox').keyup(function() { 
    // ... ? 
});

7条回答
爱死公子算了
2楼-- · 2018-12-31 16:31

$("#editable").on('keydown keyup mousedown mouseup',function(e){
		   
       if($(window.getSelection().anchorNode).is($(this))){
    	  $('#position').html('0')
       }else{
         $('#position').html(window.getSelection().anchorOffset);
       }
 });
body{
  padding:40px;
}
#editable{
  height:50px;
  width:400px;
  border:1px solid #000;
}
#editable p{
  margin:0;
  padding:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div contenteditable="true" id="editable">move the cursor to see position</div>
<div>
position : <span id="position"></span>
</div>

查看更多
登录 后发表回答