引入 JS

<script>
    // 创建隐藏内容的复制按钮
    document.addEventListener('DOMContentLoaded', initCopyButton);
    function initCopyButton() {
        const util = {
            newButton: function (cp) {
                cp.style.display = '0';
                let text = cp.getAttribute('text');
                text = text[0] === '\n' ? text.slice(1) : text;
                const button = document.createElement('a');
                button.href = '#'
                button.innerHTML = cp.getAttribute('name');
                button.className = 'btn btn-primary';
                button.onclick = () => {
                    const originName = button.innerHTML;
                    const actionResult = this.copy(text) ? '成功' : '失败';
                    button.innerHTML = '复制' + actionResult;
                    setTimeout(() => button.innerHTML = originName, 250);
                    return false;
                };
                cp.parentNode.insertBefore(button, cp);
            },
            copy: function (text) {
                let result = false;
                const target = document.createElement('pre');
                target.style.opacity = '0';
                target.textContent = text;
                document.body.appendChild(target);
                try {
                    const range = document.createRange();
                    range.selectNode(target);
                    window.getSelection().removeAllRanges();
                    window.getSelection().addRange(range);
                    document.execCommand('copy');
                    window.getSelection().removeAllRanges();
                    result = true;
                } catch (e) {
                    console.log('copy failed.');
                }
                document.body.removeChild(target);
                return result;
            }
        };
        document.querySelectorAll('cp').forEach(cp => util.newButton(cp));
    }
</script>

添加按钮

以 html 形式将以下内容写入文章中,即可创建复制按钮

<cp name="复制静夜思" text="
       静夜思
床前明月光,疑是地上霜。
举头望明月,低头思故乡。
"></cp>