让用户在jquery中复制文本并重写粘贴 [英] get the users copied text in jquery and rewrite the paste

查看:105
本文介绍了让用户在jquery中复制文本并重写粘贴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让用户复制文本并重写他们粘贴的内容。

Im trying to get the users copied text and rewrite what they paste.

示例....

<p>This is some awesome text that i wrote</p>

说用户复制单词awesome text

say the user copies the words "awesome text"

我想用awesome text这个词加上 - 来自mywebsite.com

I want to take the words "awesome text" and add on " - from my mywebsite.com"

所以现在当用户粘贴从我复制的文本时网站它会说,真棒文字 - 来自我的mywebsite.com

So now when users paste this text copied from my website it will say, "awesome text - from my mywebsite.com"

我用Google搜索了这是我到目前为止所得到的 http://jsfiddle.net/YD88T/

I've googled around this is what I got so far http://jsfiddle.net/YD88T/

推荐答案

也许这段代码可以解决问题。它会在用户实际复制之前将您的文本附加到用户选择。

Perhaps this code could do the trick. It appends your text to the user selection before the user actually copies it.

jQuery.fn.addtocopy = function(usercopytxt) {
    var options = {htmlcopytxt: '<br>More: <a href="'+window.location.href+'">'+window.location.href+'</a><br>', minlen: 25, addcopyfirst: false}
    $.extend(options, usercopytxt);
    var copy_sp = document.createElement('span');
    copy_sp.id = 'ctrlcopy';
    copy_sp.innerHTML = options.htmlcopytxt;
    return this.each(function(){
        $(this).mousedown(function(){$('#ctrlcopy').remove();});
        $(this).mouseup(function(){
            if(window.getSelection){    //good times
                var slcted=window.getSelection();
                var seltxt=slcted.toString();
                if(!seltxt||seltxt.length<options.minlen) return;
                var nslct = slcted.getRangeAt(0);
                seltxt = nslct.cloneRange();
                seltxt.collapse(options.addcopyfirst);
                seltxt.insertNode(copy_sp);
                if (!options.addcopyfirst) nslct.setEndAfter(copy_sp);
                slcted.removeAllRanges();
                slcted.addRange(nslct);
            } else if(document.selection){  //bad times
                var slcted = document.selection;
                var nslct=slcted.createRange();
                var seltxt=nslct.text;
                if (!seltxt||seltxt.length<options.minlen) return;
                seltxt=nslct.duplicate();
                seltxt.collapse(options.addcopyfirst);
                seltxt.pasteHTML(copy_sp.outerHTML);
                if (!options.addcopyfirst) {nslct.setEndPoint("EndToEnd",seltxt); nslct.select();}
            }
        });
  });
}

我从这里拿走了它: http://naviny.by/js/main.min.js

演示(选择至少25个字符)

A demo (select at least 25 characters)

这篇关于让用户在jquery中复制文本并重写粘贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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