我找到了大量关于如何在contentEditable
元素中设置插入符号位置的跨浏览器的好答案,但没有一个是关于如何首先获得插入符号位置的。
我想要做的是知道keyup
的div中插入符号的位置。因此,当用户输入文本时,我可以随时知道contentEditable
元素中插入符号的位置。
<div id="contentBox" contentEditable="true"></div>
$('#contentbox').keyup(function() {
// ... ?
});
发布于 2016-04-05 18:28:52
$("#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>
发布于 2019-01-24 02:55:12
参加派对有点晚了,但以防其他人还在挣扎。在过去的两天里,我在谷歌上找到的搜索结果都没有找到任何有用的东西,但我想出了一个简洁优雅的解决方案,无论你有多少嵌套的标签,它都会一直起作用:
function cursor_position() {
var sel = document.getSelection();
sel.modify("extend", "backward", "paragraphboundary");
var pos = sel.toString().length;
if(sel.anchorNode != undefined) sel.collapseToEnd();
return pos;
}
// Demo:
var elm = document.querySelector('[contenteditable]');
elm.addEventListener('click', printCaretPosition)
elm.addEventListener('keydown', printCaretPosition)
function printCaretPosition(){
console.log( cursor_position(), 'length:', this.textContent.trim().length )
}
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
它选择所有的方式回到段落的开头,然后计算字符串的长度以获得当前位置,然后撤消选择以将光标返回到当前位置。如果您想对整个文档(多个段落)执行此操作,请将paragraphboundary
更改为documentboundary
或您的情况下的任何粒度。查看more details的应用编程接口。干杯!:)
发布于 2014-06-02 16:29:51
https://stackoverflow.com/questions/3972014
复制相似问题