在JavaScript中,如何选择网站上的文本,复制它(通过Control+C、Command+C或Edit Copy),并让JavaScript将一行或两行附加到剪贴板,以便用户粘贴时显示所复制的内容以及额外的行?
此外,是否可能仅在网站的某些
此外,是否可能仅在网站的某些
中执行此操作?如果是,如何实现?
我开发了一个脚本来实现这个功能(这里是有关此内容的博客文章):
<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>
我在faqs.org网站上看到了这个[1],也很好奇。他们使用了来自tynt.com的一些javascript。我还发现了一个ask-metafilter答案[2],指向了另一个javascript。它们应该是很好的起点。我自己还没有解决,但我认为你可以将事件监听器附加到特定的div。
您可以使用execCommand("Copy")
和execCommand("Paste")
的组合来实现您想要的功能。
以下内容应该会对您有所帮助:
http://www.geekpedia.com/tutorial126_Clipboard-cut-copy-and-paste-with-JavaScript.html