【问题标题】:Prevent text from being inserted inside html in contenteditable防止文本插入到 contenteditable 中的 html 中
【发布时间】:2018-06-14 04:14:24
【问题描述】:

我有一个内容可编辑的 div,里面有一个链接:

<div contenteditable>
  <a id="a">[$special.value$]</a>
</div>

如果用户在最后的字段中单击并开始输入,则新文本将插入到 &lt;a&gt; 内部而不是之后。

<div contenteditable>
  <a id="a">[$special.value$] new text added here</a> instead of here
</div>

如何确保在&lt;a&gt; 之外添加新文本?

我尝试在&lt;a&gt; 上添加contenteditable="false",但这增加了许多其他怪癖。

现在,我能想到的最好办法是在链接之前和之后使用 &amp;zwnj; - 这可以防止将文本添加到 &lt;a&gt; 中,但它会使光标移动有点奇怪(你必须左/右移动额外时间)

div[contenteditable] {
  border: 1px solid #aaa;
}

a {
  color: red;
}
Normal
<div contenteditable>
  <a id="a">[$special.value$]</a>
</div>

With zwnj
<div contenteditable>
  <a id="a">[$special.value$]</a>&zwnj;
</div>

【问题讨论】:

  • 为什么在&lt;a&gt;标签内没有链接到任何地方的元素?
  • 它甚至可能是&lt;span&gt; 或其他一些html,问题是其中添加了新文本
  • 我没有注意到光标有什么奇怪的地方。

标签: javascript contenteditable


【解决方案1】:

&lt;div&gt; 中创建另一个元素(例如&lt;span&gt;)并将其contenteditable 设置为true。然后设置&lt;div&gt;向左浮动,&lt;span&gt;显示为块元素。

div.container {
  border: 1px solid #aaa;
}

a {
  float: left;
  color: red;
}

span[contenteditable] {
  display: block;
  width:   100%;
}
<div class="container">
  <a href="#" id="a">[$special.value$]</a>
  <span contenteditable></span>
</div>

【讨论】:

    【解决方案2】:

    您是否考虑过在contenteditable 获得焦点时暂时删除a 元素,然后在它失去焦点时将其重新加入?

    let old = "";
    document.querySelector("div[contenteditable]").addEventListener("focus", function(){
      old = this.innerHTML; // Store the current data
      this.innerHTML = "";  // clear out the element
    });
    
    document.querySelector("div[contenteditable]").addEventListener("blur", function(){
      // Set the new content to the old concatenated with the current
      this.innerHTML = old + this.textContent;
    });
    div[contenteditable] {
      border: 1px solid #aaa;
    }
    
    a { color: red; }
    <div contenteditable>
      <a id="a">[$special.value$]</a>
    </div>
    <p>...Hit [TAB] or click outside of element after typing...</p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多