Lock items in contenteditable = "true" div

I have a contenteditable div that is used for user input, when a button is clicked, it shows options for replacing certain words. First, it removes all html and creates span elements where the word can be replaced. The markup of these words is different, and I run into some problems.

  • When you click immediately before or after an interval and enter text, the text will have the same markup as the range. It is very difficult to add words to a string that has only a range. I thought about this, filling in the blanks with   but it looks weird.
  • The user can click on the range and change it, I would prefer the user to click on the range and select the replace or ignore option before replacing it. In other words, it needs to be blocked. I thought about doing this using the capurig keyboard, and if it comes from a range, then e.preventDefault () is on it, but it's a bit of a pain to program it.

So my questions are:

Is there an easy way to block the span element in contenteditable that does not involve key capture and preventing Default (have not tried it yet and are not even sure it will work)?

When you click or move the cursor directly next to a range and input text, it will be part of the range, is there any way that it is not part of the range? Fill a range with   may work, but it looks weird when the range is the first word in a string. To illustrate this, I posted an example html file below:

 <!DOCTYPE html> <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="content-type"> <title>Example</title> </head> <body> <div contenteditable="true"></div> <script type="text/javascript"> document.getElementsByTagName("div")[0] .innerHTML="<span style='color:green'>hello</span>" </script> </body> </html> 
+4
source share
2 answers

As for the blocking elements in the contenteditable div; I use spaces that need to be locked and they do not fire keydown events, so set the event to a div and check the range if it is a locked element.

I use google closure library to get range:

 goog.events.listen(document.getElementById("userInput"),//userInput= contenteditable div [goog.events.EventType.KEYDOWN, goog.events.EventType.PASTE], function(e){ if(32<e.keyCode&&e.keyCode<41){//page up,down,home,end and arrow return; } var el=goog.dom.Range.createFromWindow() .getContainerElement(); if(el.className.indexOf("locked")!==-1){ e.preventDefault(); } }); 

I will consider filling a locked range with & nbsp; if spaces did not exist before or after the element and did not place it here after receiving the decision.

Filling in the blanks without checking is completed, as extra spaces will be deleted later. It looks funny, but it's better not to add text.

0
source

Check the range inside the editable container contenteditable = "false". This will solve both problems at the same time.

+1
source

Source: https://habr.com/ru/post/1479933/


All Articles