javascript - 使用零宽度空间和 execCommand ("copy"时发生冲突)

标签 javascript jquery css

我会尽可能简单地解释我的意思。 我想向用户显示一个弹出窗口,其中包含要复制的 url 链接(动态创建),例如(实际上文本要长得多):

var url = "http://myweb.com/en/​728,​1,​5a2a16,​5e4f4f,​4a3f7a,​12,​12";

为了正确显示它(我的意思是很好地打破这一行以适合弹出窗口)我使用零宽度空间 所以代码看起来像这样:

var url = "http://myweb.com/en/​728,​​1,​​5a2a16,​​5e4f4f,​​4a3f7a,​​12,​​12";
$("#content").html(url);

接下来,当弹出窗口出现时,我可以通过选择所有内容并使用 ctrl+c 来复制此文本,或者只需单击一个按钮来自动复制,我将其用于一段谷歌代码:

window.getSelection().removeAllRanges();
var seltext = document.querySelector("#content");  
var range = document.createRange();  
range.selectNode(seltext);  
window.getSelection().addRange(range);  
var successful = document.execCommand("copy"); 

问题开始于我复制 URL(无论哪种方式)并将其粘贴到浏览器中并按回车键,之后我得到了这个:

The requested URL myweb.com/en/728,​1,​5a2a16,​5e4f4f,​4a3f7a,​12,​12,​12 was not found on this server.

当我删除零宽度空格字符并使用 $("#content").text(url); (文本而不是 html)时,问题消失了,但随后我遇到了另一个问题正确的长换行。有人知道如何让这些东西一起工作吗? (因此该行将在我想要的区域中断 - 在逗号和复制功能之后不会复制任何额外的字符,只有用户在屏幕上看到的内容)

最佳答案

我认为最好的解决方案是为此使用 CSS。 注意在Firefox&IE中必须将anchor的display属性设置为block,否则无法断词。

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Test 1</title>
        <style type="text/css">
            a { word-break: break-all; width: 150px; display: block;}
        </style>
    </head>

    <body>
        <a href="http://www">http://www.domain.com/TherearemanyvariationsofpassagesofLoremIpsumavailable,butthemajorityhavesufferedalterationinsomeform,byinjectedhumour,orrandomisedwordswhichdon'tlookevenslightlybelievable.IfyouaregoingtouseapassageofLoremIpsum,youneedtobesurethereisn'tanythingembarrassinghiddeninthemiddleoftext.AlltheLoremIpsumgeneratorsontheInternettendtorepeatpredefinedchunksasnecessary,makingthisthefirsttruegeneratorontheInternet.Itusesadictionaryofover200Latinwords,combinedwithahandfulofmodelsentencestructures,togenerateLoremIpsumwhichlooksreasonable.ThegeneratedLoremIpsumisthereforealwaysfreefromrepetition,injectedhumour,ornoncharacteristicwordsetc</a>
    </body>
</html>

这种方法将为您提供 CTRL+CexecCommand("copy") 的解决方案,因为 url 并没有真正改变。

如果您不能使用这种方法 - 您应该在调用 execCommand 之前从字符串中删除空白字符,以确保复制剥离的字符串。

如果您真的想要 execCommand(而不是 CSS 版本),您可以使用以下代码:

    <!doctype html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <title>Test 2</title>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
            <style type="text/css">
                a { word-break: break-all; width: 150px; display: block;}
                .hidden {font-size:1px; width: 1px; height: 1px; overflow: hidden; position: absolute; left: -100000px; top: -10000px;}
            </style>
            <script type="text/javascript">
            var preventDoubleCall = false;
            function copyWrapper() {
                if (preventDoubleCall) {
                    preventDoubleCall = false;
                    return;
                }
                $('.hidden').text($('a').text().replace(/,/g, "This is the text to replace"))
                window.getSelection().removeAllRanges();
                var seltext = $(".hidden")[0];
                var range = document.createRange();
                range.selectNode(seltext);
                window.getSelection().addRange(range);
                preventDoubleCall = true;
                var successful = document.execCommand("copy");
            }
            $(function(){
                $(document).bind('copy', function() {
                    copyWrapper();
                });
                $('#click-to-copy').click(function() {
                    copyWrapper();
                });
            });
            </script>
        </head>

        <body>
            <a href="http://www">http://www.domain.com/TherearemanyvariationsofpassagesofLoremIpsumavailable,butthemajorityhavesufferedalterationinsomeform,byinjectedhumour,orrandomisedwordswhichdon'tlookevenslightlybelievable.IfyouaregoingtouseapassageofLoremIpsum,youneedtobesurethereisn'tanythingembarrassinghiddeninthemiddleoftext.AlltheLoremIpsumgeneratorsontheInternettendtorepeatpredefinedchunksasnecessary,makingthisthefirsttruegeneratorontheInternet.Itusesadictionaryofover200Latinwords,combinedwithahandfulofmodelsentencestructures,togenerateLoremIpsumwhichlooksreasonable.ThegeneratedLoremIpsumisthereforealwaysfreefromrepetition,injectedhumour,ornoncharacteristicwordsetc</a>
            <div class="hidden"></div>
            <button id="click-to-copy">Click here to copy</button>
        </body>
    </html>

您应该将替换行更改为您想要替换的文本(换行符/逗号/等等)。 我不得不使用“视野之外”的方法,因为你不能复制隐藏元素上的文本。 无论您选择了哪个部分,代码都会复制您想要的文本。如果你想改变它,那么文本将只包含你选择的原始部分(而不是 anchor 内的所有文本)。

关于javascript - 使用零宽度空间和 execCommand ("copy"时发生冲突),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37635719/

相关文章:

javascript - 使用 javascript/html 从 JSON 结果中获取一段数据

javascript - fancybox v2 iframe 高度调整

javascript - WebGL : Callback hell in the resource loader

javascript - $(window).blur 事件影响 Iframe

jquery - 如何增加tinymce Iframe的高度?

jquery - 如何将icomoon图标保持在中间

javascript - 如何设置 cookie 以在第二页加载时隐藏通知栏?

复选框上的 Javascript 克隆此 div,未选中时删除此 div

javascript - 与 JQuery .change 标签斗争的初学者

jquery - CSS3 底层图像无法在 I.E. 中悬停它在 Firefox 中使用指针事件工作