我将如何使用 javascript 或 dojo 从链接或按钮实现“将 url 复制到剪贴板”而不使用 Flash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16526814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:01:02  来源:igfitidea点击:

How would I implement 'copy url to clipboard' from a link or button using javascript or dojo without flash

javascriptdojo

提问by Raghuram

I got stucked in implementing this feature on my web application. All the other possibilities are mostly by using flash content. Could someone explain how I can achieve it by using plain javascript or by Dojo.

我坚持在我的 Web 应用程序上实现此功能。所有其他可能性主要是通过使用 Flash 内容。有人可以解释我如何通过使用普通的 javascript 或 Dojo 来实现它。

回答by caffeinated.tech

I have been working on the exact same issue for a while. For me flash isn't a viable solution so I came up with this simple work around:

我一直在研究完全相同的问题一段时间。对我来说,Flash 不是一个可行的解决方案,所以我想出了这个简单的解决方法:

<button onclick="prompt('Press Ctrl + C, then Enter to copy to clipboard','copy me')">Click to Copy</button>

<button onclick="prompt('Press Ctrl + C, then Enter to copy to clipboard','copy me')">Click to Copy</button>

It requires some extra work on the users end but at least it doesn't require flash or external libraries.

它需要在用户端做一些额外的工作,但至少它不需要闪存或外部库。

example fiddle

示例小提琴

回答by Soumitra Sarkar

Html

html

<a class="" data-toggle="tooltip" data-placement="top" title="Copy profile Link" onclick="copy_to_clipboard('<%=public_profile_url(user.public_id)%>')">
<i class="fa fa-copy"></i>

Css

css

#url_public_id{
  display: none;
}

JS

JS

function copy_to_clipboard(link) {
    $("#url_public_id").show()
    var Url = document.getElementById("url_public_id");
    Url.select();
    document.execCommand("copy");
    $("#url_public_id").hide()
    alert("Copied URL ");
}

回答by frank

Wanted to implement the same feature. Ended up using https://clipboardjs.com.

想要实现相同的功能。最终使用https://clipboardjs.com

new Clipboard('.btn', {
  text: function() {
    return window.location.href;
  }
});

Works well

效果很好