未加星标

Javascript Copy and Paste

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

Javascript Copy and Paste

In a previous tutorial we saw how you can create a copy and paste button using jQuery and the ZeroClipboard flash extension . The problem with this is that it requires flash. As most of the web is moving away from flash and some people don't even have flash installed on their browser we need another solution.

The reason flash was used to copy and paste is mainly down to browser compatibility, now with most browsers now supporting the API to enable you to copy and paste directly using javascript using the Web API document.execCommand .

View the demo to see how the API works

HTML

First we add the HTML to the page we need a textbox to enter the content we want to copy, a button that will have the click event to start the copy process and a textarea where we can test the copy is successful by pasting the contents into it.

<div>
<input type="text" id="text-to-copy" placeholder="Enter text" />
<button id="copy-text">Copy</button>
<span id="copied-text" style="display: none;">Copied!</span>
</div>
<div>
<textarea name="paste-area" id="paste-area" cols="30" rows="10" placeholder="Paste it here"></textarea>
</div> Copy Text

To copy the text we first need to add a click event to the button.

document.getElementById('copy-text').addEventListener('click', function(e){
// Click event
});

Inside the click event we need to select the text inside the textbox.

document.getElementById('text-to-copy').select();

With the text selected we can now use the execCommand('copy') to copy the text to the clipboard.

copied = document.execCommand('copy');

The return of this method will be a boolean on if the text was copied or not, you can then check this boolean value to display a message if it was able to be copied.

// Add click event
document.getElementById('copy-text').addEventListener('click', function(e){
e.preventDefault();
// Select the text
document.getElementById('text-to-copy').select();
var copied;
try
{
// Copy the text
copied = document.execCommand('copy');
}
catch (ex)
{
copied = false;
}
if(copied)
{
// Display the copied text message
document.getElementById('copied-text').style.display = 'block';
}
}); Browser Compatibility Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari copy / cut 42 41 (41) 9 29 10

Back to top

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaHTMLjQueryChromeFirefox
分页:12
转载请注明
本文标题:Javascript Copy and Paste
本站链接:http://www.codesec.net/view/480703.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(31)