• 轻松实现通过js复制内容和js修改粘贴板中内容


    实现点击不是input或者texterea框的时候复制功能,需求有时复制按钮需要放置一些特殊的内容,比如一个选中的树节点,如果需要获取到它的id的时候,还有可能会让你在粘贴前对id进行判断,如果已经存在亦或者是根节点等特殊情况再次做操作的情况。

    主要通过以下两个API 进行实现,兼容性可以点击链接查看。

    当一个HTML文档切换到设计模式时,document暴露 execCommand 方法,该方法允许运行命令来操纵可编辑内容区域的元素。(摘自MDN)

    是可编辑区域可被操纵。所以需要创建一个临时的input框或者textarea,如果内容需要保存格式时使用textarea

    execCommand

    execCommand兼容性

    const btn = document.querySelector("#btn");
    btn.addEventListener("click", function() {
        // 创建一个input框
        const input = document.createElement("input");
        // 设置 input框内容
        input.setAttribute("value", "copy content");
        // 添加到body元素中
        document.body.appendChild(input);
    
        // 将新添加进去的input元素进行选中
        input.select();
    
        // 为input添加监听事件方便对剪贴板内容进行二次修改
        input.addEventListener("copy", function(event) {
            // 使用ClipboardApi来设置剪贴板里的内容
            // 参考张鑫旭的博客, 需要的文末有地址
            var clipboardData = event.clipboardData || window.clipboardData;
            if (!clipboardData) {
                return;
            }
            var text = window.getSelection().toString();
            if (text) {
                event.preventDefault();
                clipboardData.setData("text/plain", text + "
    
     我是添加进来的内容");
            }
        });
    
        // 执行复制操作
        if (document.execCommand("copy")) {
            console.log("复制成功");
        } else {
            console.log("复制失败");
        }
    
        // document.execCommand('copy') 如果内容复制的不全
        // document.execCommand('copy')前先进行document.execCommand('selectAll')选中所有内容即可
    
        // 移除input框
        document.body.removeChild(input);
    });
    

    张鑫旭博客

  • 相关阅读:
    通过jsonp解决ajax的跨域请求问题
    为php安装redis扩展模块并测试
    浅谈使用 PHP 进行手机 APP 开发(API 接口开发)(转)
    touch事件记录
    jquery mobile 问题
    background总结,转自http://www.daqianduan.com/3302.html
    博客收集
    css3 border-radius 总结
    css3 box-shadow 总结
    angular 重置表单
  • 原文地址:https://www.cnblogs.com/daixixi/p/12155092.html
Copyright © 2020-2023  润新知