简体   繁体   English

更改Delete / Backspace键的功能

[英]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. 我有一个功能,当按Delete键时,将选定的文本包装在一个范围内。 The class of the span is red with a line-through, to show it's been "deleted." 跨度的类别为红色并带有直行,以表明它已被“删除”。

CSS: CSS:

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

JavaScript: 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. 这是一个contenteditable文本,所以当我按下删除键,自然它会删除选定的文本,但仍创造了<span>元素。 Is there any way to disable the traditional function of the delete key so that the text remains but still wraps with the <span> ? 有什么方法可以禁用删除键的传统功能,以便保留文本但仍用<span>包裹吗?

e.preventDefault() should work. e.preventDefault()应该可以工作。

Also, you should use the <del> HTML element instead of <span> with a class attached. 另外,应使用<del> HTML元素而不是带有附加类的<span>

Test out this testcase: https://jsfiddle.net/jdshq796/ 测试此测试用例: 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. 您需要在代码中添加e.preventDefault(),以确保不会触发事件的默认操作。

$(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);
              }
           } 
        }
     });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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