如何使用JavaScript自动将文本附加到复制的文本

9
在JavaScript中,如何选择网站上的文本,复制它(通过Control+C、Command+C或Edit Copy),并让JavaScript将一行或两行附加到剪贴板,以便用户粘贴时显示所复制的内容以及额外的行?
此外,是否可能仅在网站的某些
中执行此操作?如果是,如何实现?

有趣的事实:福克斯新闻做到了,非常流畅。(尝试使用CTRL-Copying) - ZJR
3个回答

10

我开发了一个脚本来实现这个功能(这里是有关此内容的博客文章):

<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>

1

1

问题是,你如何检测用户何时复制了某些内容?然后我可以从你发给我的页面中找出如何实现它。 - Jared
6
jQuery内置了出色的复制/粘贴检测功能:http://www.devcurry.com/2009/07/detect-copy-paste-and-cut-operations-on.html。 - James Skidmore

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接