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

1.应用场景

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

2.学习/操作

code

index.html

 

<!DOCTYPE html>
<html>
<head>
    <title>document 节点 - 复制内容</title>
</head>
<body>
    <div id="target">
        <input id='content' type="text" name="content" value='这是要复制的内容~~'>
        <input type="button" value="Copy" οnclick="doCopy()">
    </div>
    <script type="text/javascript">

        function copyText(dom) {
            var text = dom.value;
            dom.focus();
            dom.select();

            // 当前是否有选中文字
            if (document.queryCommandEnabled('copy')) {
                var success = document.execCommand('copy');
                console.log('Copy Ok');
            } else {
                console.log('queryCommandEnabled is false');
            }
        }

        function doCopy(){
            //浏览器是否支持 copy 命令(选中内容复制到剪贴板)
            if (document.queryCommandSupported('copy')) {
                var targetDom = document.getElementById('content');
                copyText(targetDom);
            }else{
                console.log('浏览器不支持');
            }
        }
    </script>
</body>
</html>

截图:

 

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

 

 

 

 

后续补充

...

3.问题/补充

TBD

4.参考

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

后续补充

...

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章