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

後續補充

...

 

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