Javascript 在副本上附加链接

Javascript Append Link on Copy

本文关键字:链接 副本 Javascript      更新时间:2023-09-26

我在我的博客中添加了Javascript附加链接,这意味着当有人从我的网站复制文本时,它还将复制博客文章URL并添加Read more标签,所以我想修改这个脚本,并让它像,当有人复制至少20个字符时,那么这段代码将在剪贴板中复制Read more标签, 如果用户复制少于 20 个单词,则此脚本不应正常工作。因此,如果有人能做到这一点,那将是非常有帮助的。谢谢

原文 -

<script type="text/javascript">
function addLink() {
    var body_element = document.getElementsByTagName('body')[0];
    var selection;
    selection = window.getSelection();
    var pagelink = "<br /><br /> Read more at: <a href='"+document.location.href+"'>"+document.location.href+"</a><br />"; // change this if you want
    var copytext = selection + pagelink;
    var newdiv = document.createElement('div');
    newdiv.style.position='absolute';
    newdiv.style.left='-99999px';
    body_element.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    selection.selectAllChildren(newdiv);
    window.setTimeout(function() {
        body_element.removeChild(newdiv);
    },0);
}
document.oncopy = addLink;
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</script>

试试这个。当选择的长度小于20时,该函数将返回选择。

<script type="text/javascript">
function addLink() {
    var body_element = document.getElementsByTagName('body')[0];
    var selection;
    selection = window.getSelection();
    if(selection.toString().length<20)
     {
       return selection;
      }
    var pagelink = "<br /><br /> Read more at: <a href='"+document.location.href+"'>"+document.location.href+"</a><br />"; // change this if you want
    var copytext = selection + pagelink;
    var newdiv = document.createElement('div');
    newdiv.style.position='absolute';
    newdiv.style.left='-99999px';
    body_element.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    selection.selectAllChildren(newdiv);
    window.setTimeout(function() {
        body_element.removeChild(newdiv);
    },0);
}
document.oncopy = addLink;
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</script>