Copy text to clipboard using Zero Clipboard in asp.net

浪子不回头ぞ 提交于 2019-12-01 18:06:27
<html>
<body>
<button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">
Copy to Clipboard</button>
<script src="ZeroClipboard.js"></script>
<script src="main.js"></script>
</body>
</html>

//In Main.js file
// main.js
var clip = new ZeroClipboard( document.getElementById("copy-button"), {
moviePath: "/path/to/ZeroClipboard.swf"
} );

clip.on( 'load', function(client) {
// alert( "movie is loaded" );
} );

clip.on( 'complete', function(client, args) {
this.style.display = 'none'; // "this" is the element that was clicked
alert("Copied text to clipboard: " + args.text );
} );

clip.on( 'mouseover', function(client) {
// alert("mouse over");
} );

clip.on( 'mouseout', function(client) {
// alert("mouse out");
} );

clip.on( 'mousedown', function(client) {

// alert("mouse down");
} );

clip.on( 'mouseup', function(client) {
// alert("mouse up");
} );
<html>
<body>
        <script type="text/javascript" src="ZeroClipboard.js"></script>

        <div id="d_clip_button" style="border:1px solid black; padding:20px;">Copy To Clipboard</div>

        <script language="JavaScript">
            var clip = new ZeroClipboard.Client();
            var myTextToCopy = "Hi, this is the text to copy!";
            clip.setText( myTextToCopy );
            clip.glue( 'd_clip_button' );
        </script>
</body>
</html>

First of all, you're trying to pick element by wrong id. Since you use webforms, correct way is:

getElementById('<%=TextBox2.ClientID%>')

Also, following unobtrusive js style good solution might look like:

$().ready(function () {
    ZeroClipboard.setDefaults({ moviePath: "/Scripts/ZeroClipboard.swf" });

    var clip = new ZeroClipboard(document.getElementById('YourButtonId')); //or '<%=YourButton.ClientID%>' if you use asp.net button

    clip.on('complete', function (client, args) {
        alert("Copied text to clipboard: " + args.text);
    });
});

Also your button should have data attribute data-clipboard-target(actually there're three ways to do it). Setting data-attributes to webforms control is tricky, so you might want to avoid using asp.net button here and do it like:

<input type="button" value="clickme" id="YourButtonId" data-clipboard-target="<%=TextBox2.ClientID %>"/>

Enjoy!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!