我正在尝试编写一个在有人尝试将某些文本粘贴到(例如:文本区域/可编辑div)时运行的函数,如果该文本是函数,则该函数应检查文本是否大于10个字符应该只保留前10个字符并将其粘贴到(文本区域/可编辑Div)。
我尝试使用剪贴板api来处理此问题,但是我找不到粘贴修改后的文本的方法。
HTML
<div id='editableDiv' contenteditable='true'>Paste</div>
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);
JS FIDDLE https://jsfiddle.net/swL8ftLs/12/
希望结果仅将第一个字符粘贴到div区域
答案 0 :(得分:0)
您必须阻止默认操作,而要手动插入(已修改的)内容。 MDN's page on the paste
event有一个示例(在这种情况下,使文本大写):
// (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();
});
<div class="source" contenteditable="true">Try copying text from this box...</div>
<div class="target" contenteditable="true">...and pasting it into this one</div>
答案 1 :(得分:0)
执行substring(0, 10
操作之后,只需将内容添加到div
textContent
属性中,您可以从event.target
访问该属性:
function handlePaste (event) {
var clipboardData, pastedData;
// Stop data actually being pasted into div
event.stopPropagation();
event.preventDefault();
// Get pasted data via clipboard API
clipboardData = event.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
if(pastedData.length > 10){
pastedData = pastedData.substring(0, 10);
}
event.target.textContent = pastedData;
}
document.getElementById('target').addEventListener('paste', handlePaste);
<div id='source' contenteditable='true'>This is more than 10 characters</div>
<div id='target' contenteditable='true'>Paste here</div>
答案 2 :(得分:0)
您可以使用document.execCommand
和insertHTML
function handlePaste (e) {
var clipboardData, pastedData;
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
e.preventDefault()
if (pastedData.length > 10) {
console.log("its longer", pastedData.length);
pastedData = pastedData.substring(0, 10);
}
document.execCommand("insertHTML", false, pastedData);
}
document.getElementById('editableDiv').addEventListener('paste', handlePaste);
<div id='editableDiv' contenteditable='true'>Paste</div>