【问题标题】:weird beheviour after removing an element from contentEditable从 contentEditable 中删除元素后的奇怪行为
【发布时间】:2014-08-04 18:30:29
【问题描述】:

我在contentEditable <div> 中有一些<div>class=tgg

<div>class=tgg 也是 contentEditable(这是必需的)。

当用户删除特定的.tgg div 的内容时会出现问题。似乎 div 被删除了;但是在开始输入后,会在 chrome 中创建一个与.tgg 相同样式的跨度,并将输入的文本包装在其中。这会产生应避免的不良影响。

这是我的代码:

HTML:

<div id="tarea" contentEditable="true" class="tarea" autocorrect="false" spellCheck="off">
<div class="tgg">Vedant Terkar</div> 
Creates another <div class="tgg">Fiddle</div> 
for all <div class='tgg'>SO</div> Users.

</div>

<textarea id="opc" rows="5" cols="97">
</textarea>

CSS:

.tarea{
    width:99%;
    height:300px;
    overflow:auto;
    clear:both;
    display:inline-block;
    border:1px solid #000;
    padding:5px;
    outline:none;
    color:#333;
    }
    .tarea .tgg{
    background:#99d;
    color:#fff;
    padding:1px;
    border:1px solid #77b; 
    display:inline-block;
    }

JS:

$(document).ready(function(){
    $("#tarea").keyup(function(e){
    var html=$(this).html().toString().trim();
    html=html.split("<br>").join("\n");
    html=html.split("&nbsp;").join(" ");
        $("#opc").val(html);
        $(this).find(".tgg").each(function(){
        $(this).attr("contenteditable","true");
        });
    });
    $("#tarea").trigger("keyup");
});

DEMO


这就是我想说的:

如您所见,这是代码的输出:

当您将光标(插入符号)放在 fiddlefor 之间并使用 BackSpaceDel 删除 fiddle 时,删除如下:

但是现在,如果您开始输入任何内容,它将不会以纯文本形式生成,而是会在 &lt;span&gt; 中,例如:

我正在使用chrome。对于不同的browser,输出可能会有所不同。谁能告诉我如何解决这个问题? 欢迎任何建议。提前致谢 :)!

【问题讨论】:

  • 这取决于浏览器如何生成元素。您在一个浏览器中修复了一件事情,它会在其他浏览器中导致另一种不需要的行为。
  • @undefined,没错。有没有办法让它在所有浏览器中统一工作?如果不能,你能帮我用 chrome 解决这个问题吗?
  • @VedantTerkar 见帖子。谢谢

标签: javascript jquery html css contenteditable


【解决方案1】:

试试

$(document).ready(function(){
    $("#tarea").on("keyup", function(e){
    var html=$(this).html().toString().trim();
    html=html.split("<br>").join("\n");
    html=html.split("&nbsp;").join(" ");
        $("#opc").val(html);
        $(this).find(".tgg").each(function(){
        $(this).attr("contenteditable","true");
        });
        // replace `font` with `text` within `font`
        // TODO: change caret (cursor) position ,
        // following `replaceWith()` call ,
        // to position _after_ replaced element
        $("font").each(function(i, el) {
          $(el).replaceWith($(el).text());
        });        
    }).trigger("keyup");
});

jsfiddle http://jsfiddle.net/guest271314/h7h97/

How to move cursor to end of contenteditable entity

Set cursor position on contentEditable <div>

Get caret (cursor) position in contentEditable area containing HTML content

【讨论】:

  • 非常感谢伙计:)。这解决了这个问题。但是你能不能也让它在 FireFox 中工作?这在那里不起作用。 +1 努力。
  • 修复了它:)!谢谢。但是您能解释一下在.replaceWith() 工作后如何使光标正常工作吗?
  • @VedantTerkar 查看帖子中的链接,TODO。也许是一个有用且独特的问题本身?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
相关资源
最近更新 更多