我想在HTML5中使用复制到剪贴板功能,但不使用闪存.可能吗?怎么样?
我尝试使用JavaScript实现copy-to-clipboad函数,但它不起作用:
function Copytoclipboard() {
var body = document.body,
range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
document.execCommand('Copy');
} catch (e) {
range.selectNode(el);
sel.addRange(range);
document.execCommand('Copy');
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
range.execCommand('Copy');
}
}
Run Code Online (Sandbox Code Playgroud)
Var*_*ant 26
您可以使用HTML5 clipboard api http://www.htmlgoodies.com/html5/other/working-with-clipboard-apis-in-html5-web-apps.html#fbid=eh9tM7GHJWF
但请注意,截至目前,并非所有浏览器都完全支持它:http://caniuse.com/#feat=clipboard
Tre*_*vor 18
更新:此解决方案也适用于Safari.
我认为还没有针对此的非Flash,跨浏览器解决方案.这是一个至少可以在Chrome,Firefox和Edge的最新版本中运行的解决方案:
function copyText(text){
function selectElementText(element) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}
var element = document.createElement('DIV');
element.textContent = text;
document.body.appendChild(element);
selectElementText(element);
document.execCommand('copy');
element.remove();
}
var txt = document.getElementById('txt');
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
copyText(txt.value);
})Run Code Online (Sandbox Code Playgroud)
<input id="txt" />
<button id="btn">Copy To Clipboard</button>Run Code Online (Sandbox Code Playgroud)
注意:尝试使用此解决方案复制空字符串或仅为空格的字符串将不起作用.
Zen*_*cha 17
它无法正常工作,因为它需要用户交互,例如点击.否则,document.execCommand将无法正常工作.您也可能想检查clipboard.js,这是一个非常容易的库,可以将文本复制到不需要Flash的剪贴板.
小智 9
将文本插入剪贴板的功能:
function copyStringToClipboard (string) {
function handler (event){
event.clipboardData.setData('text/plain', string);
event.preventDefault();
document.removeEventListener('copy', handler, true);
}
document.addEventListener('copy', handler, true);
document.execCommand('copy');
}
Run Code Online (Sandbox Code Playgroud)
如果您不希望在复制之前选择文本字段的内容,那么以下两行解决方案至少可以在Chrome 56和Edge中使用,但是我敢打赌它也可以在其他浏览器中使用。
function clickListener() {
document.getElementById('password').select();
document.execCommand('copy');
}
document.getElementById('copy_btn').addEventListener('click', clickListener);Run Code Online (Sandbox Code Playgroud)
<input id=password value="test">
<button id=copy_btn>Copy</button>Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/uwd0rm08/
| 归档时间: |
|
| 查看次数: |
53778 次 |
| 最近记录: |