• 文字复制和选择效果


    文字复制

    • 仅能复制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);
    })
    
  • 相关阅读:
    SQL学习
    设计模式学习之简单工厂
    c#读写操作3
    SQL存储过程学习
    c# xml的读写
    SQL存储过程实例
    存储过程分页
    搞双显示器
    转:用药的七种心理误区
    lp提了一个非常让偶非常郁闷的要求……
  • 原文地址:https://www.cnblogs.com/grey-zhou/p/10042883.html
Copyright © 2020-2023  润新知