我使用此代码为我复制的文字添加了更多链接,但会忽略换行符和格式:
<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>
如何保存它们?
答案 0 :(得分:2)
选择被复制为纯文本,为了保留换行符和格式,您必须将所选文本作为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;
答案 1 :(得分:0)
在按照更正(Working Demo)之后猜猜它是否有效:
function addLink() {
var body_element = document.getElementsByTagName("body")[0];
var selection = window.getSelection();
var pagelink = '< br/> < br/> Mai multe Bancuri pe: http://bancuricubarbatisifemei.blogspot.com/ <br/>';
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;
<强> 编辑: 强>
尝试使用pre
代替div
&amp;换行符(' \ n ')以保留换行符。 (Updated Demo)
function addLink() {
var body_element = document.getElementsByTagName("body")[0];
var selection = window.getSelection();
var pagelink = '\n\nMai multe Bancuri pe: http://bancuricubarbatisifemei.blogspot.com/\n';
var copytext = selection + pagelink;
var newdiv = document.createElement('pre');
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;