9

在 JavaScript 中,您如何选择网站上的文本、复制它(通过 Control+C、Command+C 或编辑复制)并让 JavaScript 在剪贴板上附加一两行,这样当用户粘贴时,他们复制的内容是显示以及额外的行?

此外,这是否可能仅在<div>站点的某些区域内进行?如果是这样,怎么做?

4

3 回答 3

9

我开发了一个脚本来做到这一点(这里是关于这个的博客文章):

<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> &copy; MySite.com";

    selection.selectAllChildren(newdiv);
    window.setTimeout(function () { body_element.removeChild(newdiv); }, 200);
});
</script>
于 2013-12-24T10:15:07.543 回答
1

您可以使用execCommand("Copy")和的组合execCommand("Paste")来完成您想要的。

这应该可以帮助您:

http://www.geekpedia.com/tutorial126_Clipboard-cut-copy-and-paste-with-JavaScript.html

于 2009-07-31T21:28:19.250 回答
1

我在 faqs.org 网站 [1] 上看到了这个,也很好奇。他们使用一些来自 tynt.com 的 javascript。我还发现了一个指向不同 javascript 的 ask-metafilter 答案 [2]。它们应该是很好的起点。我自己还没有解决它,但我希望你可以将事件监听器附加到有问题的 div 上。

  1. http://www.faqs.org/faqs/tv/sat-n​​ight-live/deep-thoughts/
于 2009-10-30T15:52:15.367 回答