Gee*_*nja 1 html javascript clipboard jquery clipboarddata
我的要求:当用户从我的网页复制一些内容时,带有文本的一些HTML标记和回车符也将被复制。我需要修改剪贴板中的复制内容,即删除回车键和HTML标签。
到目前为止,我已经尝试过: 即使使用jQuery,我也已捕获了副本并获得了剪贴板的内容。参见下面的代码。
$(document).bind('copy', function () {
//getting clipboard content
var selectedText = window.getSelection().toString();
//removing carriage retun from content
selectedText = selectedText.replace(/<\/?[^>]+(>|$)/g, "");
//Trying to set data in clipboard
window.clipboardData.setData(selectedText); //Throws error
}
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试使用设置剪贴板中的setData时window.clipboardData.setData(selectedText);,将引发错误。
问题:
1)我是否使用正确的功能(即setData()修改剪贴板内容)?
2)有人可以让我知道如何在这里修改剪贴板的内容吗?
And*_* H. 15
当前接受的答案过于复杂,并且会导致在复制后删除用户选择的奇怪行为。
这是一个更简单的解决方案:
document.addEventListener('copy', function(e){
var text = window.getSelection().toString().replace(/[\n\r]+/g, '');
e.clipboardData.setData('text/plain', text);
e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
小智 5
有两件事我能查到。
e传递,而不是在window.如需进一步参考,请复制 Event MDN
document.addEventListener('copy', function(e) {
console.log('copied');
e.clipboardData.setData('text/plain', 'Hello World!');
e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,我对copy事件做了什么,我绑定了一个函数,即在运行时copyToClipboard创建一个textarea,将修改后的剪贴板数据复制到此文本区域,然后执行“ CUT”命令(以避免对复制事件进行递归调用)。最后在finally块中删除textarea元素。
码:
$(document).bind('copy', function () {
var text = window.getSelection().toString().replace(/[\n\r]+/g, '');
copyToClipboard(text);
});
function copyToClipboard(text) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed";
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("cut");
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}
Run Code Online (Sandbox Code Playgroud)