复制后加上自定义版权信息等信息
禁止复制
禁止粘贴
第一种在选择的文本后拼接其他字符串;第二种将选择的内容赋值为空字符串。
拼接或重置完毕后,将新文本加入一个新建的标签中,目的是为了获得新的内容、取消之前选取的内容,得到新内容后移除该新建的元素。
在复制的内容后面添加版权信息:
function handleCopy() {
var selection = window.getSelection(); //selection为用户初始选择的内容
//pagelink为自定义的任意内容,此处为本站的转载权限
var pagelink = "<br /><br />------------------------------<br />来源:F2td - Fly 2 The Dream - www.f2td.com<br />作者:Hanna<br />原文链接: " + document.location.href+"<br />版权声明:本站文章除注明转载外,均为本站原创或编译,转载请注明出处!";
var copytext = selection + pagelink; //拼接后的新内容
var newdiv = document.createElement('div'); //新建标签
newdiv.style.position = 'absolute'; //设置style保证该元素不可见
newdiv.style.left = '-99999px';
document.body.appendChild(newdiv); //添加元素
newdiv.innerHTML = copytext; //将拼接后的字符串赋值给新元素的内容
selection.selectAllChildren(newdiv); //指定新标签的子元素为新选择内容
window.setTimeout(function () { //新内容复制完毕,移除新元素
document.body.removeChild(newdiv);
}, 100);
}
document.oncopy = handleCopy;
(推荐)方法1. 处理复制事件:
document.oncopy = function(){return false};
方法2. 将复制的内容重置为空:
function handleCopy() {
var selection = window.getSelection();
var copytext = "";
var newdiv = document.createElement('div');
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext; //将空字符串添加到新元素中,则复制的内容失效
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
document.body.removeChild(newdiv);
}, 100);
}
document.oncopy = handleCopy;
document.onpaste = function(){return false};
oncopy属性用来获取或设置当前元素的copy事件的事件处理函数。
onpaste 属性用来获取或设置当前元素的paste事件的事件处理函数。
返回一个 Selection 对象,表示用户选择的文本范围或光标的当前位置。
把指定元素的所有子元素设为选中区域,并取消之前的选中区域。
- END -