简体   繁体   English

Chrome execCommand'insertHTML'当插入符在节点内部时,将跨度插入到节点外部

[英]Chrome execCommand 'insertHTML' inserts span outside of node when caret is inside it

My task is to insert an empty span node within a contentEditable div at current caret position. 我的任务是在当前插入符号位置的contentEditable div中插入一个空的span节点。

The following gives me no problems on Firefox 22.0: 以下内容在Firefox 22.0上没有任何问题:

HTML 的HTML

<div class="parent" contentEditable=true>
    <div>text</div>
</div>

Javascript Java脚本

$('.parent').on("keyup", function(e){
    if (e.which == 73) {
       node = '<span class="new"></span>';
       document.execCommand('insertHtml', null, node);
   }
});

To reproduce: Place caret at some point of the word 'text', then press 'i' key to insert an empty span at current selection. 重现:将插入号放在单词'text'的某个位置,然后按'i'键在当前选择处插入一个空白范围。

See: http://jsfiddle.net/amirisnino/pZecx/2/ 请参阅: http//jsfiddle.net/amirisnino/pZecx/2/

Example: 例:

When pressing 'i' key in the middle of the word 在单词中间按“ i”键时

Expected result: 预期结果:

<div class="parent" contentEditable=true>
    <div>tei<span class="new"></span>xt</div>
</div>

What happens instead? 会发生什么呢?

<div class="parent" contentEditable=true>
    <div>teixt</div>
    <span class="new"></span>
    <div><br></div>
</div>

Any help with this would be greatly appreciated. 任何帮助,将不胜感激。 Thank you in advance. 先感谢您。

You can make the contenteditable attribute of span element as false. 您可以将span元素的contenteditable属性设置为false。 In order to achieve your expectation, you have to move the last two lines outside of the if-condition. 为了达到您的期望,您必须将最后两行移到if条件之外。 Here it is: 这里是:

$('.parent').on("keyup", function(e){
    if (e.which == 73) {
         node = '<span contenteditable="false" class="new"></span>';
         document.execCommand('insertHtml', null, node);
       }
       content = $(this).html()
       $('.result').text(content)

});

Does this work? 这样行吗?

$('.parent div').append(node);

instead of this: 代替这个:

document.execCommand('insertHtml', null, node);

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

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