JavaScript复制到剪贴板

    技术2022-07-11  121

    "Copy to clipboard" functionality is something we all use dozens of times daily but the client side API around it has always been lacking; some older APIs and browser implementations required a scary "are you sure?"-style dialog before the content would be copied to clipboard -- not great for usability or trust.  About seven years back I blogged about ZeroClipboard, a solution for copying content to the clipboard in a more novel way...

    我们每天都使用数十次“复制到剪贴板”功能,但一直缺乏围绕它的客户端API。 在将内容复制到剪贴板之前,某些较旧的API和浏览器实现要求使用吓人的“确定吗?”样式的对话框,这对可用性或信任性不利。 大约七年前, 我在博客中发布了ZeroClipboard ,这是一种以更新颖的方式将内容复制到剪贴板的解决方案...

    ...and by novel way I mean using Flash.  Hey -- we all hate on Flash these days but functionality is always the main goal and it was quite effective for this purpose so we have to admit it was a decent solution.  Years later we have a better, Flash-free solution:  clipboard.js.

    ...而且我的意思是使用Flash。 嘿-这些天,我们都讨厌Flash,但是功能始终是主要目标,并且对于此目的它非常有效,因此我们必须承认这是一个不错的解决方案。 几年后,我们有了一个更好的,不依赖Flash的解决方案: 剪贴板.js 。

    View Demo 观看演示

    The clipboard.js API for copy to clipboard is short and sweet.  Here are a few uses:

    复制到剪贴板的剪贴板.js API很简短。 这里有一些用途:

    复制和剪切Textarea和输入的值 (Copying and Cutting Values of Textarea and Input)

    /* Textarea - Cut hello Cut */ var clipboard = new Clipboard('.copy-button'); /* Input - Copy Copy */ var clipboard = new Clipboard('.copy-button');

    复制元素innerHTML (Copying Element innerHTML)

    /* HTMLElement - Copy hello Copy */ var clipboard = new Clipboard('.copy-button');

    Target和Text功能 (Target and Text Functions)

    // Contents of an element var clipboard = new Clipboard('.copy-button', { target: function() { return document.querySelector('#copy-target'); } }); // A specific string var clipboard = new Clipboard('.copy-button', { text: function() { return 'clipboard.js is awesome!'; } });

    大事记 (Events)

    var clipboard = new Clipboard('.btn'); clipboard.on('success', function(e) { console.log(e); }); clipboard.on('error', function(e) { console.log(e); }); View Demo 观看演示

    No Flash with a simple API and working in all major browsers makes clipboard.js a huge win for the web and its users.  The days of Flash shimming functionality on the client side are over -- long live web technology!

    没有使用简单的API且可以在所有主要浏览器中使用的Flash,使得Clipper.js对于网络及其用户而言是一个巨大的胜利。 客户端上的Flash匀场功能的时代已经过去-长期存在的Web技术!

    翻译自: https://davidwalsh.name/clipboard

    相关资源:JavaScript复制内容到剪切板示例
    Processed: 0.009, SQL: 9