admin管理员组

文章数量:1400863

I have an conteneditable with predefined text inside:

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>

I have an conteneditable with predefined text inside:

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>

I want to prevent users from deleting <span class="some-class">Dont delete me!</span> from it.

I guess I should check what text is being deleted when user press back space on onChange event. But I don't know how to check if deleted content is just on letter like H or the whole div <span class="some-class">Dont delete me!</span>

Share Improve this question edited May 10, 2017 at 15:14 Scott Marcus 65.9k6 gold badges54 silver badges80 bronze badges asked May 10, 2017 at 15:11 sir_Ksir_K 5183 gold badges9 silver badges21 bronze badges 3
  • Can I ask why you have content you don't want edited in a content editable element? – Craicerjack Commented May 10, 2017 at 15:14
  • 1 Please don't link to external code when you can easily add it here. – Scott Marcus Commented May 10, 2017 at 15:14
  • @Craicerjack this is very specific case, where user can add some predefined values that he/she shouldn't be able to deleted latter in process. – sir_K Commented May 10, 2017 at 15:48
Add a ment  | 

1 Answer 1

Reset to default 9

Instead of assigning contenteditable=true to the entire container, break down the contents into separate span elements and assign it there like so:

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

Edit: If you don't want to change the markup, you can use jQuery to search for the string of text that isn't supposed to be deleted and then make sure it persists any attempts to remove it.

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

.some-class {
  background: yellow;
  padding: 0px 5px;
}
<script src="https://ajax.googleapis./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>

本文标签: javascriptPrevent user from deleting specific text from inputStack Overflow