javascript - 求教一个js拷贝文本的问题
PHP中文网
PHP中文网 2017-04-10 16:28:31
[JavaScript讨论组]

就是简单的点击拷贝,好像很多网站都有复制代码这个按钮。但是好像说很多浏览器不支持,要用flash,现在这个问题一般都是怎么解决的

PHP中文网
PHP中文网

认证0级讲师

全部回复(3)
伊谢尔伦

long ago都是需要引入flash通过调用flash的api访问clipboard的,巨恶心..既然现在abobe自己都不推荐flash了,自然有办法。

https://zenorocha.github.io/clipboard.js/
depende on Selection and document.execCommand API

伊谢尔伦
<SCRIPT>
function CopyAll(T)
{
T.focus()
T.select()
if (document.all){
therange=T.createTextRange()
therange.execCommand("Copy") //复制
}
}
</SCRIPT>
<INPUT TYPE="BUTTON" VALUE="复制" onclick="CopyAll(text1)" >
<TEXTAREA NAME="text1" COLS="40" ROWS="5">(内容测试)</TEXTAREA>
<TEXTAREA  COLS="40" ROWS="5">(你可以在这里粘帖内容)</TEXTAREA>
迷茫

he JavaScript document.execCommand('copy') support has grown, see the links below for browser updates:

IE10+ (although this document indicates some support was there from IE5.5+).
Google Chrome 43+ (~April 2015)
Mozilla Firefox 41+ (shipping ~September 2015)
Opera 29+ (based on Chromium 42, ~April 2015)
Simple Example
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');

copyTextareaBtn.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.select();

try {

var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);

} catch (err) {

console.log('Oops, unable to copy');

}
});


<textarea class="js-copytextarea">Hello I'm some text</textarea>


<button class="js-textareacopybtn">Copy Textarea</button>

详见http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号