日常小记

JS点击复制页面内容

<p class="pad" id="pdd">123456</p>

<script>
            (function() {
                pdd.addEventListener('click', function() {
                   //设置id为pdd的区域的点击属性
                    var copyDom = document.querySelector('#pdd');
                    //找到id为pdd的内容并创建选中范围
                    var range = document.createRange();
                    range.selectNode(copyDom);
                    //移除剪切板中内容
                    window.getSelection().removeAllRanges();
                    //添加新的内容到剪切板
                    window.getSelection().addRange(range);
                    //复制
                    var successful = document.execCommand('copy');

                    try {
                        var msg = successful ? "" : "failed";
                        alert('复制成功 : ' + msg);
                    } catch (err) {
                        alert('Oops , unable to copy!');
                    }
                })
            })()
            </script>

js代码需放在要复制的内容的下方

回复

This is just a placeholder img.