第一条使用两种方法对文章进行粘贴追加信息~~~
方法一:
①监听copy事件,然后将隐藏盒子中的信息添加到其中;
②结合window.selection()方法;
③浏览器兼容情况是主流浏览器IE8以上;
④线上demo http://jsfiddle.net/jp6nhmxf/ ;
⑤使用:复制一段文本再粘贴就会出现 pagelink中的内容 。
主要JS code
function addLink() {
//Get the selected text and append the extra info
var selection = window.getSelection(),
pagelink = '\n\n Read more at: ' + document.location.href,
copytext = selection + pagelink,
newdiv = document.createElement('div');
//hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
//insert the container, fill it with the extended text, and define the new selection
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function () {
document.body.removeChild(newdiv);
}, 100);
}
document.addEventListener('copy', addLink);
方法二:
①监听copy事件,然后修改剪贴板中的内容,也就是clipboard使用;
②结合window.clipboardData.setData()方法;
③浏览器兼容情况是IE4以上(换言之只针对于IE);
④线上demo http://jsfiddle.net/m56af0je/ (IE模式下起效);
主要JS code
function addLink(event) {
event.preventDefault();
var pagelink = '\n\n Read more at: ' + document.location.href,
copytext = window.getSelection() + pagelink;
if (window.clipboardData) {
window.clipboardData.setData('Text', copytext);
}
}
document.addEventListener('copy', addLink);
⑤另外疑问点来了,使用clipboard能在其他浏览器(比如谷歌/火狐/safari)中工作吗?
主要JS code
function addLink(event) {
event.preventDefault();
var pagelink = '\n\n Read more at: ' + document.location.href,
copytext = window.getSelection() + pagelink;
(event.clipboardData || window.clipboardData).setData('Text', copytext);
}
document.addEventListener('copy', addLink);
区别在 window.clipboarddata <--> event.clipboardData
亲测在兼容模式、极速模式、谷歌、火狐、IE等浏览器中均测有效!
第二条使用的方法跟第一条类似~~~
主要JS code
/**
* @description 添加版权
*/
const addCopyright = () => {
const genCopy = () => {
return [
'',
'',
'作者:张宇童',
'链接 [文章复制添加版权](<a href="/posts/emlog-132">http://www.zyt8.cn/?post=132</a>) ',
'来源:张宇童 - 温馨技术博客',
'著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。',
]
}
$('.content-reset').on('copy', function (event) {
if (!window.getSelection) {
return
}
let copyString = window.getSelection().toString()
if (copyString.length < 128) {
return
}
if ('object' === typeof event.originalEvent.clipboardData) {
event.originalEvent.clipboardData.setData('text/html', copyString + genCopy().join(''))
event.originalEvent.clipboardData.setData('text/plain', copyString + genCopy().join('\n'))
event.preventDefault()
return
}
$('body').append(`${copyString}${genCopy().join('')}`)
window.getSelection().selectAllChildren($('#pipeFixCopy')[0])
setTimeout(function() {
$('#pipeFixCopy').remove()
}, 200)
})
}
找一个空白地方复制粘贴测试,~~本人只在极速模式下测通过,其他未测~~
敬请留意~~