JavaScript - 浏览器中点击拷贝内容

拼搏现实的明天。 2023-02-18 08:20 47阅读 0赞

1.应用场景







主要用于浏览器中点击button进行内容的拷贝, 节省一点时间, 以及了解实现的过程

2.学习/操作







1.文档阅读

https://wangdoc.com/javascript/dom/document.html

https://developer.mozilla.org/zh-CN/docs/Web/API/Document/queryCommandEnabled

 

2.实践/使用



index.html


 


<!DOCTYPE html>


<html>


<head>


    <title>document 节点 - 复制内容</title>


</head>


<body>


    <div id=”target”>


        <input id=’content’ type=”text” name=”content” value=’这是要复制的内容~~’>


        <button id=”copy” type=”button” value=”Copy” >Copy</button>


    </div>


    <script>


        function copyText(dom) {


            var text = dom.value;


            dom.focus();


            dom.select();


 


            // 当前是否有选中文字


            var success = document.execCommand(‘copy’);


            if (success) {


                console.info(‘Copy Ok’);


            } else {


                console.error(‘Copy Fail!’);


            }


        }


 


        function doCopy(){


            //浏览器是否支持 copy 命令(选中内容复制到剪贴板)


            if (document.queryCommandSupported(‘copy’)) {


                var targetDom = document.getElementById(‘content’);


                copyText(targetDom);


            }else{


                console.error(‘浏览器不支持’);


            }


        }


 


        document.getElementById(“copy”).addEventListener(“click”, function(){


            // document.getElementById(“content”).value = ”Hello World”;


            doCopy();


        });


    </script>


</body>


</html>


截图:

 

之后按下ctrl+v即可粘贴内容

 

 

 

 

后续补充

3.问题/补充







TBD

4.参考







https://wangdoc.com/javascript/dom/document.html

后续补充

发表评论

表情:
评论列表 (有 0 条评论,47人围观)

还没有评论,来说两句吧...

相关阅读