移动端复制到粘贴板

移动端复制到粘贴板

前端时间做移动端碰到了关于复制到粘贴板的问题,搜到了下面两种方法,第一种亲测在手机上是有用的,第二种等待你萌在移动端测试是否成功告诉我哈!

法一

HTML:

<input type="text" id="text_input" /> <button type="button" id="copy_text">copy</button>

js:

var inputElem = document.getElementById('text_input'); var btnElem = document.getElementById('copy_text'); btnElem.addEventListener('click', function() { if(!document.execCommand) { console.error('copy unsupport'); return; } inputElem.select(); var result = document.execCommand('copy'); if(result) { console.log('copy success'); } else { console.error('copy fail'); } });

注意事项

  • 检测当前环境是否支持命令API,这一步不可或缺。
  • 浏览器环境不支持命令API,需要合理地提示用户手动进行复制操作。所以,一定不能设置文本元素 user-select: none;,这样会使文本不能被选择。
  • 表单元素必须处于被选中状态,即调用 inputElement.select() 方法,文本元素没有 select() 方法。
  • 经测试,不能使用 display: none; 或 visibility: hidden; 来隐藏表单元素。所以,只能将此表单元素,定位至可以见区域之外。
  • 必须表单元素有用,如果不是表单元素,建议新建input标签,然后把val赋给input,在进行操作。需要灵活实现

更多方案

  • clipboard.js:不依赖flash的一个插件。实现原理和上面的例子是类似的,使用插件可以简化很多开发工作。

引用:https://www.cnblogs.com/xianxianxxx/p/8056396.html

法二

`






移动端复制到粘贴板!


哈哈你没看错,就是复制的这里





`

posted @ 2018-05-16 11:03  在水伊人  阅读(561)  评论(0)    收藏  举报