简体   繁体   中英

Change the function of the Delete/Backspace Key

I have a function that wraps selected text in a span when the delete key is pressed. The class of the span is red with a line-through, to show it's been "deleted."

CSS:

     .deleted {
     text-decoration:line-through;
     color:red;
       }

JavaScript:

    $(document).keydown(function(e) {
      (e) ? keycode = e.keyCode : keycode = event.keyCode;
      if (keycode == 8 || 46) {
        var span = document.createElement("span");
        span.className = "deleted";
        if (window.getSelection) {
           var sel = window.getSelection();
           if (sel.rangeCount) {
              var range = sel.getRangeAt(0).cloneRange();
              range.surroundContents(span);
              sel.removeAllRanges(); 
              sel.addRange(range);
              }
           } 
        }
     });

This is a contenteditable text, so when I press the delete key, naturally it deletes the selected text, but still creates the <span> element. Is there any way to disable the traditional function of the delete key so that the text remains but still wraps with the <span> ?

e.preventDefault() should work.

Also, you should use the <del> HTML element instead of <span> with a class attached.

Test out this testcase: https://jsfiddle.net/jdshq796/

You need to stop the the default action of the event.

You need to add e.preventDefault() into your code that insure that default action of the event will not be triggered.

$(document).keydown(function(e) {
       e.preventDefault();
      (e) ? keycode = e.keyCode : keycode = event.keyCode;
      if (keycode == 8 || 46) {
        var span = document.createElement("span");
        span.className = "deleted";
        if (window.getSelection) {
           var sel = window.getSelection();
           if (sel.rangeCount) {
              var range = sel.getRangeAt(0).cloneRange();
              range.surroundContents(span);
              sel.removeAllRanges(); 
              sel.addRange(range);
              }
           } 
        }
     });

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