简体   繁体   English

有IMG元素时如何设置插入位置?

[英]How to set the caret position when there is an IMG element?

I have a content editable div like this: 我有一个像这样的内容可编辑div:

<div contenteditable="true">test1<img src="img.jpg"></img>test2</div>

Now, if I set the caret on position 5, I get this (the vertical line is the caret in the code below): 现在,如果我将插入符号设置在第5位,我得到了这个(垂直线是下面代码中的插入符号):

<div contenteditable="true">test1|<img src="img.jpg"></img>test2</div>

and if I set the caret on position 6, I get this: 如果我把插入符号放在第6位,我会得到这个:

<div contenteditable="true">test1<img src="img.jpg"></img>t|est2</div>

How can I set the caret right next to the IMG element? 如何在IMG元素旁边设置插入符号? I want to get something like this: 我想得到这样的东西:

<div contenteditable="true">test1<img src="img.jpg"></img>|test2</div>

When the div has the content: "before <img> after", then basically there are 3 elements in it: 0.text:"before ", 1.img, 2.text: " after", and you want to be at the beginning of the #2: 当div有内容时:“在<img>之后”,那么基本上它有3个元素:0.text:“before”,1.img,2.text:“after”,你想要在#2的开头:

 function setCaretPositionAfter1stImg(elemId) { var el = document.getElementById(elemId); if(el != null) { el.focus(); var range = document.createRange(); var sel = window.getSelection(); range.setStart(el, 2); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } setCaretPositionAfter1stImg("ed"); 
 <div contenteditable="true" id="ed">test1<img src="img.jpg"/>test2</div> 

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

相关问题 如何在 contenteditable 中的 img 之后放置插入符号 - How to position caret to after an img in a contenteditable 如何在 contenteditable 元素(div)中设置插入符号(光标)position? - How to set the caret (cursor) position in a contenteditable element (div)? 如何保持插入符号在 contenteditable 元素中的位置 - How to keep the position of the caret in contenteditable element 如何在子节点的contenteditable中设置插入符位置? - How to set caret position in contenteditable with childs nodes? 如何在contentedable span中设置插入位置然后发送Keys? - How to set caret position in contenteditable span and then sendKeys? 如何在extJS tagfield中设置插入符号位置 - How to set caret position in extJS tagfield 如何在可编辑的iframe上设置插入符号位置? - How to set the caret position on an editable iframe? 在contentEditable div中的inserted元素后面设置插入位置 - Set caret position right after the inserted element in a contentEditable div 在Chrome的contenteditable元素的节点内将插入符位置设置为零 - Set caret position to zero inside node of contenteditable element in chrome 更改可编辑div元素的html结构时,如何恢复选择/插入符号位置? - How to restore the selection / caret position when the html structure of an editable div element is changed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM