
在国内转载别人的原创文章属于非常普遍的现象,但是一般都不会注明出处,曾记得知乎的效果是最棒的,在网上找了很久,终于找到了可以通过技术手段,添加代码来实现复制自动加版权信息的方法,虽然不能有效的解决问题,但会有一些帮助。
网上很多代码都是把版权加在了最前面,这样用户体验不好,终于寻得一个能加到尾部的,并且做了字数判断,少于80个字符的不加版权,超过80个字符的自动加版权。
原理
1. 监听 copy 事件
2. 使用 window.getSelection() 获取选中的文本
3. 使用 clipboardData.setData 操作剪贴板的内容
$("body").bind('copy', function (e) {
if (typeof window.getSelection == "undefined") return; //IE8 or earlier...
var body_element = document.getElementsByTagName('body')[0];
var selection = window.getSelection();
//if the selection is short let's not annoy our users
if (("" + selection).length < 80) return;
//create a div outside of the visible area
//and fill it with the selected text
var newdiv = document.createElement('div');
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
body_element.appendChild(newdiv);
newdiv.appendChild(selection.getRangeAt(0).cloneContents());
//we need a <pre> tag workaround
//otherwise the text inside "pre" loses all the line breaks!
if (selection.getRangeAt(0).commonAncestorContainer.nodeName == "PRE") {
newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
}
newdiv.innerHTML += "<br /><br />来源:「蓝卡」 链接: <a href='"
+ document.location.href + "'>"
+ document.location.href + "</a>";
selection.selectAllChildren(newdiv);
window.setTimeout(function () { body_element.removeChild(newdiv); }, 200);
});
更新了吗
学习了