js复制文本

曹え 5811 发布于:2023-03-02 08:12:55

两种方法,一种是复制文本框里面的文字,第二种是复制div里面的文本


<!-- html -->

        <input type="text" id="copyVal" value="被复制的内容" />
        <button onclick="myCopy">点击复制</button>
        
// 方法一:点击按钮复制文本框内容
    function myCopy(){
        var copyVal = document.getElementById('copyVal');
        copyVal.select();
        document.execCommand('copy');
    }
<!-- html -->
<div id="copyInner">被复制的内容</div>
 <button onclick="myCopy">点击复制</button>

    // 方法二:点击按钮复制div标签内容
    function myCopy(){
        const range = document.createRange();
        range.selectNode(document.getElementById('copyInner'));
        const selection = window.getSelection();
        if(selection.rangeCount > 0) selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('copy');
    }


觉得有用请点个赞吧!
2 305