如何在使用javascript粘贴之前修改复制的文本

Jil*_*ilo 5 javascript dom

我试图编写一个函数,当一个人尝试将一些文本粘贴到(例如:文本区域/可编辑 div)时运行,该函数应该检查文本是否大于 10 个字符,如果文本是该函数应该只保留前 10 个字符并将它们粘贴到(文本区域/可编辑 Div)。

我尝试使用剪贴板 API 来处理此问题,但我找不到粘贴修改后的文本的方法。

超文本标记语言

<div id='editableDiv' contenteditable='true'>Paste</div>
Run Code Online (Sandbox Code Playgroud)

JS

function handlePaste (e) {
        var clipboardData, pastedData;

        // Get pasted data via clipboard API
    clipboardData = e.clipboardData || window.clipboardData;
    pastedData = clipboardData.getData('Text');

    //if pasted text is longer then 10 chars
       if (pastedData.length > 10) {
            console.log("its longer", pastedData.length);
            //we take only the first 10 chars
            var limitedData = pastedData.substring(0, 10);
   //  i want this text to be pasted
}

}

document.getElementById('editableDiv').addEventListener('paste', handlePaste);
Run Code Online (Sandbox Code Playgroud)

JS 小提琴 https://jsfiddle.net/swL8ftLs/12/

我希望结果仅将第一个字符粘贴到 div 区域

T.J*_*der 8

您必须阻止默认操作,而是手动插入(修改的)内容。MDN 关于该paste事件的页面有一个示例(在本例中,将文本设为大写):

// (From https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event)

const target = document.querySelector('div.target');

target.addEventListener('paste', (event) => {
    let paste = (event.clipboardData || window.clipboardData).getData('text');
    paste = paste.toUpperCase();
 
    const selection = window.getSelection();
    if (!selection.rangeCount) return false;
    selection.deleteFromDocument();
    selection.getRangeAt(0).insertNode(document.createTextNode(paste));

    event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
<div class="source" contenteditable="true">Try copying text from this box...</div>
<div class="target" contenteditable="true">...and pasting it into this one</div>
Run Code Online (Sandbox Code Playgroud)