zoukankan      html  css  js  c++  java
  • 文字复制和选择效果

    文字复制

    • 仅能复制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);
    })
    
  • 相关阅读:
    [LeetCode]Sort List
    [LeetCode]Single Number II
    合并两个排序的列表
    翻转链表
    链表中倒数第k个结点
    调整数组顺序使奇数位于偶数前面
    数值的整数次方
    二进制中1的个数
    矩形覆盖
    变态跳台阶
  • 原文地址:https://www.cnblogs.com/grey-zhou/p/10042883.html
Copyright © 2011-2022 走看看