防止文本被插入html中的contenteditable

时间:2018-06-13 19:53:57

标签: javascript contenteditable

我有一个满足的div,内部是一个链接:

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

如果用户点击最后的字段并开始输入,则新文本将插入<a>内而不是之后。

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

如何确保在<a>

之外添加新文字

我尝试在contenteditable="false"上添加<a>,但这会增加许多其他怪癖。

现在,我能想到的最好的方法是在链接之前和之后使用&zwnj; - 这可以防止文本被添加到<a>内部,但它会使光标移动有点奇怪(你必须向左/向右移动一段时间)

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>

2 个答案:

答案 0 :(得分:1)

<span>内创建另一个元素(例如<div>)并将其contenteditable设置为true。然后将<div>设置为向左浮动,将<span>设置为块元素。

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

a {
  float: left;
  color: red;
}

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

答案 1 :(得分:0)

您是否考虑在a获得焦点时临时删除contenteditable元素,然后在失去焦点时将其预先挂起?

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>

相关问题