简体   繁体   English

在一个令人满意的div中获得插入符号位置

[英]Get caret positon in a contenteditable div

In a contenteditable div , I have some text and an image like He✈llo . 在一个contenteditable div ,我有一些文字和像He✈llo的图像。

But in the js file the contenteditable div is like He<img src="plane.gif">llo When I put cursor after the airplane and use window.getSelection.getRangeAt(0) then it shows cursor/caret position as 3. What I need is that it shows caret position as 24 ie reading image as an img tag and shows the position of caret at the end of the img tag. 但是在js文件中, contenteditable div就像He<img src="plane.gif">llo当我把光标放在飞机后并使用window.getSelection.getRangeAt(0)然后它将光标/插入位置显示为3。我需要的是它将插入符号位置显示为24,即将图像作为img标记读取,并在img标记的末尾显示插入符号的位置。

Is there any way to achieve this?? 有没有办法实现这个?

I made this http://plnkr.co/edit/Qlhzxsqko3coXe9iWl0r?p=preview Its not working correctly but it will give you an idea of what I am trying to say 我做了这个http://plnkr.co/edit/Qlhzxsqko3coXe9iWl0r?p=preview它工作不正常,但它会让你知道我想说的是什么

If I understood well what do you want to do, then this should resolve your problem(just click between different chars from text): 如果我理解你想做什么,那么这应该解决你的问题(只需在文本中的不同字符之间点击):

 $('p').bind('click', function(event) { finalCount = 0; var selection = window.getSelection().getRangeAt(0); var count = 0; $($(this).contents()).each(function(index, val) { if ($(val).html() == null) { count += selection.startOffset; } else { count += $(val).get(0).outerHTML.length; } if ($(val).text() == selection.startContainer.nodeValue) { console.log('found!'); finalCount = count; } }); alert(finalCount); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <p class="text" style="margin-left:5px">He <img src="http://www.micronas.com/sites/all/themes/micronas/images/icons/image-x-generic.png">llo</p> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM