简体   繁体   中英

Delete whole anchor tag in contenteditable div on one keypress

I have following HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
    </head>
    <body>
        <div id="edit" contenteditable>
            This is <a href="#">link</a> that is editable.
        </div>
    </body>
</html>

What I'm trying to do is a very simple text editor where you can put in links (they would get turned into html via JS) but when you hit backspace in the back or delete in front of them, I want it to disappear at once (not deleting anchor text letter by letter).

How would one go about it? My steps with Javascript would be sth like this:

  1. When pressing Backspace key, detect if </a> is before the cursor, if so run regex on the section before cursor, pick a first match and replace it with blank space.
  2. The opposite, detect if Delete key is pressed, check if <a ... > is in front of it and remove it as well.

I'm just not quite sure how to put this in code and also if I can run regex and have it recognize the text in contenteditable area. I'd like to avoid any heavy external libraries because the text editor will not really do much more besides this.

If anybody wants to fork my Codepen here it is . Thanks for any advice.

If you've already got the method down to pass in the string and re-assign the value of the contenteditable section, here's an example of how to structure the regex.

 var textblock = document.getElementById('edit') function testContent(deletetype) { // deletetype == "delete" || "backspace" var txt = textblock.innerHTML.toString().trim(), rgxstring = "<a[^<]+<\\\\/a>", rgx if (deletetype == "delete") { rgxstring = "^" + rgxstring } else { rgxstring += "$" } rgx = new RegExp(rgxstring, "i") console.log(txt, txt.match(rgx)) textblock.innerHTML = txt.replace(rgx, "") } testContent("backspace") 
 <div id="edit" contenteditable> This is <a href="#">link</a> </div> 

There is a clean way to solve this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
    </head>
    <body>
        <div id="edit" contenteditable>
            This is <a href="#" contenteditable="false">link</a> that is editable.
        </div>
    </body>
</html>

Adding a contenteditable="false" will register the anchor as a whole and not letter by letter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM