execCommand的复制

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <div class="" id='article'>
            这是一段复制文字
        </div>
        <button type="button" name="button" id='button'>复制</button>
    </body>
    <script type="text/javascript">
        document.getElementById('button').onclick=function () {
            if (document.selection) {
                //IE
                var range = document.body.createTextRange();
                range.moveToElementText(document.getElementById('article'));
                range.select();
            } else if (window.getSelection) {
                var range = document.createRange();
                range.selectNode(document.getElementById('article'));
                const selection = window.getSelection();
                if(selection.rangeCount > 0) selection.removeAllRanges();
                window.getSelection().addRange(range);
            }
            document.execCommand('copy');

        }
    </script>
</html>
execCommand在ios低版本不兼容。
posted @ 2017-09-16 12:28  地铁程序员  阅读(629)  评论(0编辑  收藏  举报