js实现网页端复制功能

实现网页端复制功能:

<div id="copyInput" style="display:none;">
  <form>
    <input id="pageUrlInput" type="text" class="form-control alert-input-url"
    style="border: 1px solid transparent; box-shadow: inset 0 0 0;" />
  </form>
</div>

<script>
        //微课分享
        var dLabel = document.getElementById("dLabel");

        dLabel.addEventListener('click', function (event) {
            var pageUrl = window.location.href;
            var copyTextarea = document.getElementById("pageUrlInput");
            copyTextarea.value = pageUrl;

            $("#shareSuccess").css({ "display": "" });
            $("#copyInput").css({ "display": "" });
            copyTextarea.select();
            try {
                var successful = document.execCommand('copy');
                if (successful) {
                    document.getElementById('alert-share-text').innerText = "复制当前网页链接成功,现在您可以发送给朋友进行分享!";
                } else {
                    document.getElementById('alert-share-text').innerText = "当前浏览器不允许访问剪切板,请复制当前网页链接发送给朋友进行分享!";
                }

                setTimeout(function () {
                    $("#shareSuccess").css({ "display": "none" });
                }, 3000)

                var msg = successful ? 'successful' : 'unsuccessful';
                console.log('Copying text command was ' + msg);

            } catch (err) {
                console.log('Oops, unable to copy');
            }
        });
    </script>
}
原文地址:https://www.cnblogs.com/maoyazhi/p/6434915.html