如何自动将文本附加到使用JavaScript复制的文本 [英] How to automatically append text to text copied with JavaScript

查看:174
本文介绍了如何自动将文本附加到使用JavaScript复制的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,如何在网站上选择文本,复制它(通过Control + C,Command + C或编辑复制),并使JavaScript在剪贴板中附加一两行,以便当用户粘贴时,内容

In JavaScript, how can you select text on a website, copy it (by Control+C, Command+C, or Edit Copy) and have JavaScript append a line or two to the clipboard so when the user pastes, the content they copied is shown as well as the extra line?

此外,这只能在某些< div> s的网站?如果是,如何?

Also, would this be possible to do only within certain <div>s of the site? If so, how?

推荐答案

我开发了一个脚本来实现这一目标(和这里有关于此的博文):

I developed a script that does this (and here's the blog post about this):

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

这篇关于如何自动将文本附加到使用JavaScript复制的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆