撤消JS中的覆盖粘贴

mbo*_*007 11 javascript jquery undo paste

我已忽略了该paste事件。我注意到,由于阻止了事件的默认行为,因此当前无法使用Ctrl + Z撤消“粘贴”。

$(this).on('paste', function (evt) {
  // Get the pasted data via the Clipboard API.
  // evt.originalEvent must be used because this is jQuery, not pure JS.
  // /sf/answers/2088211891/
  var clipboardData = evt.originalEvent.clipboardData || window.clipboardData;
  var pastedData = clipboardData.getData('text/plain');

  // Trim the data and set the value.
  $(this).val($.trim(pastedData));

  // Prevent the data from actually being pasted.
  evt.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以覆盖撤消功能,或者可以做其他不同的操作以使Ctrl + Z起作用?

相关问题

Mun*_*nna 5

使用

document.execCommand("insertText", false, $.trim(pastedData));
Run Code Online (Sandbox Code Playgroud)

代替

 $(this).val($.trim(pastedData));
Run Code Online (Sandbox Code Playgroud)

它将保留撤消历史记录。

document.execCommand("insertText", false, $.trim(pastedData));
Run Code Online (Sandbox Code Playgroud)
 $(this).val($.trim(pastedData));
Run Code Online (Sandbox Code Playgroud)


mbo*_*007 1

我找到了一种让它发挥作用的方法。从这个答案开始,我将其更改为使用.focus()而不是.select(),这修复了粘贴。然后,为了在 Firefox 中进行粘贴工作,我必须保留不保留撤消历史记录的后备。在 Firefox 修复该错误之前,必须执行此操作(请参阅错误报告)。

function insertAtCaretTrim(element, text) {
    element[0].focus();
    // Attempt to preserve edit history for undo.
    var inserted = document.execCommand("insertText", false, $.trim(text));
  
    // Fallback if execCommand is not supported.
    if (!inserted) {
        var caretPos = element[0].selectionStart;
        var value = element.val();

        // Get text before and after current selection.
        var prefix = value.substring(0, caretPos);
        var suffix = value.substring(element[0].selectionEnd, value.length);

        // Overwrite selected text with pasted text and trim. Limit to maxlength.
        element.val((prefix + $.trim(text) + suffix).substring(0, element.attr('maxlength')));

        // Set the cursor position to the end of the paste.
        caretPos += text.length;
        element.focus();
        element[0].setSelectionRange(caretPos, caretPos);
    }
}

var $inputs = $("input");

$inputs.each(function () {
    $(this).on('paste', function (evt) {
    var clipboardData = evt.originalEvent.clipboardData || window.clipboardData;
    var pastedData = clipboardData.getData('text/plain');

    // Trim the data and set the value.
    insertAtCaretTrim($(this), pastedData);
    
    evt.preventDefault();
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" maxvalue="10" />
Run Code Online (Sandbox Code Playgroud)

代码也在 JSFIddle 中:https ://jsfiddle.net/mf8v97en/5/