<分区>
在 JavaScript 中,您如何选择网站上的文本、复制它(通过 Control+C、Command+C 或编辑复制)并让 JavaScript 将一两行附加到剪贴板,这样当用户粘贴时,内容他们复制的内容和额外的行一起显示了吗?
此外,这是否可能仅在某些 <div>
内执行?网站的?如果是,怎么办?
<分区>
在 JavaScript 中,您如何选择网站上的文本、复制它(通过 Control+C、Command+C 或编辑复制)并让 JavaScript 将一两行附加到剪贴板,这样当用户粘贴时,内容他们复制的内容和额外的行一起显示了吗?
此外,这是否可能仅在某些 <div>
内执行?网站的?如果是,怎么办?
最佳答案
我开发了一个脚本来执行此操作(以及 here's 关于此的博客文章):
<script>
$("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 < 30) return;
//create a div outside of the visible area
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 />Read more at: <a href='"
+ document.location.href + "'>"
+ document.location.href + "</a> © MySite.com";
selection.selectAllChildren(newdiv);
window.setTimeout(function () { body_element.removeChild(newdiv); }, 200);
});
</script>
关于javascript - 如何自动将文本附加到使用 JavaScript 复制的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1214928/
相关文章:
javascript - 有没有办法从 protobuf 生成 GraphQL 模式?
javascript - 如何在附加html代码后获取ready事件
javascript - 如何更改 sequelize model.findOne() 目标表?
jquery - 非 (X)HTML 属性……有什么缺点吗?
javascript - 来自 UglifyJs 的错误 : SyntaxError: Unexpected token: operator (>)
javascript - 如何替换 li 文本但保留其子元素?