文字复制和选择效果

文字复制

  • 仅能复制input内的文字
  • 有几种api(兼容问题)

这里使用典型的一种api,另,为了能复制div内的文字,就需要我们通过动态创建input来实现。

dom.addEventListener('click',e=>{
    // 创建input
    let input = document.createElement('input');
    document.body.appendChild(input);
    // 塞入内容
    input.setAttribute('value', res.innerText);
    // 选中内容
    input.select();
    // 执行复制
    document.execCommand('copy');
    // 移除掉 input
    document.body.removeChild(input);
})

文字选择

  • document.body.createTextRange
  • window.getSelection
// 选择某dom内的所有文本
function selectText(el) {
    if (document.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(el);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(el);
        selection.removeAllRanges();
        selection.addRange(range);
    } 
}

简单结合

dom.addEventListener('click',e=>{
    // 创建input
    let input = document.createElement('input');
    document.body.appendChild(input);
    // 塞入内容
    input.setAttribute('value', res.innerText);
    // 选中内容
    input.select();
    // 执行复制
    document.execCommand('copy');
    // 界面上选择文本  需放在 iput.select()之后,否则会被取消效果
    this.selectText(e.target)  
    // 移除掉 input
    document.body.removeChild(input);
})
原文地址:https://www.cnblogs.com/grey-zhou/p/10042883.html