我使用此代码向复制的文本添加阅读更多链接,但换行符和格式将被忽略:
<script type='text/javascript'>
function addLink() {
var body_element = document.getElementsByTagName('body')[0];
var selection;
selection = window.getSelection();
var pagelink = "<br/><br/> Mai multe Bancuri pe: http://bancuricubarbatisifemei.blogspot.com/ <br/>"; // change this if you want
var copytext = selection + pagelink;
var newdiv = document.createElement('div');
newdiv.style.position='absolute';
newdiv.style.left='-99999px';
body_element.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function() {
body_element.removeChild(newdiv);
},0);
}
document.oncopy = addLink;
</script>
如何保存它们?
最佳答案
所选内容将被复制为纯文本,为了保留换行符和格式,您必须将所选文本获取为 HTML。
JavaScript 代码:
function addLink() {
var selection = window.getSelection();
var htmlDiv = document.createElement("div");
for (var i = 0; i < selection.rangeCount; ++i) {
htmlDiv.appendChild(selection.getRangeAt(i).cloneContents());
}
var selectionHTML = htmlDiv.innerHTML;
var pagelink = "<br/><br/>Read more: http://www.stackoverflow.com/ <br/>";
var copytext = selectionHTML + pagelink;
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); }, 0);
}
document.oncopy = addLink;
关于javascript - 添加额外信息(版权声明/阅读更多链接)以复制文本并保留格式(换行符和颜色),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175735/