jiebba

使用

 

npm install xl_copy   // 项目中安装
import clipboard form \'xl_copy\'  // 引用
element.onclick = ()=>{     clipboard(\'test\')  // 复制 test }

 

1、介绍

    利用原生 js 写一个简单到复制到剪切板工具

    点击按钮,实现复制文本到剪切板

    用函数形式直接调用

 

2、知识梳理

    1.createTextRange() 方法

        IE 似乎不支持

    2.createRange()

        都不支持

    3.setSelectionRange(start,end,diraction)      方法可用

        选中 html 元素的内容。实现选取 ( inputElemnt 方法 )

        适用于含有 value 属性到 html 原生,如 input 等

        三个参数:开始位置,结束位置,方向

    4.select()  方法可用

        用于选中 textarea / input 的所有内容

        inputElement.select()

    5.document.execCommand(commandName,defaultUI,argument)

        copy : 复制选中内容到剪切板,存在兼容问题

        cut : 剪切内容到剪切板,存在兼容问题

 

3、代码实现

    利用 select() 方法和 document.execCommand() 来实现

export function clipboard(text) {
    let inputElement = document.createElement(\'input\');
    inputElement.value = text;
    document.body.appendChild(inputElement)
    inputElement.select()
    document.execCommand(\'copy\', true);
    inputElement.parentNode.removeChild(inputElement)
}

  

4、npm 包使用

npm install xl_copy

import clipboard form \'xl_copy\'
element.onclick = ()=>{
    clipboard(\'test\')  // 复制 test
}

  

 

想了解更多,想知道更多精华,看看我的博客吧   https://gilea.cn/

 

 https://www.cnblogs.com/jiebba

 

分类:

技术点:

相关文章:

  • 2021-12-13
  • 2021-12-19
  • 2021-10-03
  • 2021-12-13
  • 2021-12-03
  • 2021-11-05
  • 2021-11-05
  • 2021-12-03
猜你喜欢
  • 2021-12-13
  • 2021-12-03
  • 2021-12-03
  • 2021-12-03
  • 2021-12-03
  • 2021-11-05
  • 2021-12-03
相关资源
相似解决方案