阻止用户从输入中删除特定文本

时间:2017-05-10 15:11:06

标签: javascript html css

我有一个可以使用预定义文本的内容:

div{
  padding: 10px;
  border: 1px solid black;
}
.some-class{
  background: yellow;
  padding: 0px 5px;
}
<div contenteditable=true>Hello <span class="some-class">Dont delete me!</span> people!</div>

我想阻止用户从中删除<span class="some-class">Dont delete me!</span>

我想我应该检查当用户在onChange事件上按回空格时要删除的文本。但我不知道如何检查删除的内容是否仅在H或整个div <span class="some-class">Dont delete me!</span>

之类的字母上

1 个答案:

答案 0 :(得分:7)

不是将contenteditable=true分配给整个容器,而是将内容分解为单独的span元素并将其分配到那里:

&#13;
&#13;
div{
  padding: 10px;
  border: 1px solid black;
}
.some-class{
  background: yellow;
  padding: 0px 5px;
}
&#13;
<div><span contenteditable=true>Hello </span><span class="some-class" contenteditable=false>Dont delete me!</span><span contenteditable=true> people!</span></div>
&#13;
&#13;
&#13;

编辑:如果您不想更改标记,可以使用jQuery搜索不应该被删除的文本字符串,然后确保它仍然存在任何删除它的尝试

&#13;
&#13;
$('#div').on('input', function() {
  var span = $('.some-class').text();
  if (span.indexOf('Dont delete me!') < 0) {
    $('.some-class').text('Dont delete me!');
  }
});
&#13;
div {
  padding: 10px;
  border: 1px solid black;
}

.some-class {
  background: yellow;
  padding: 0px 5px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div" contenteditable=true>Hello <span class="some-class">Dont delete me!</span> people!</div>
&#13;
&#13;
&#13;