zoukankan      html  css  js  c++  java
  • 源生JS实现点击复制功能

    之前在工作中,有位同事问过我一个问题,JS如何实现点击复制功能。给他解决后现在来总结归纳一下,顺便做个笔记。

    PS:此乃本人第一篇博客(跟着同事大佬学习),涉及知识尚浅,如有任何意见和建议请告知于我。下面开始正文:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>源生JS实现点击复制功能</title>
    </head>
    <body>
    <button onclick="clkCopy()">点击复制</button>
    <input type="text" id="text" value="123">
    <script>
        function clkCopy() {
            var text = document.getElementById("text");
            text.select();
            document.execCommand('copy');
            alert("复制成功!");
        }
    </script>
    </body>
    </html>

    通过DOM元素的select()方法可以选择到<input>和<textarea>中的文字,再调用document.execCommand('copy');实现复制功能。

    那么,如果我们想要复制<div>中的内容,可以用上述方法嘛?经测试,使用上述方法点击复制<div>中的内容会报错

     

     那么我们可以使用如下方法来实现此功能:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>源生JS实现点击复制功能</title>
    </head>
    <body>
    <button onclick="clkCopyDiv()">点击复制</button>
    <div id="div">123</div>
    <script>
        function clkCopyDiv() {
            var text = document.getElementById("div");
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
            document.execCommand('copy');
            alert("复制成功!");
        }
    </script>
    </body>
    </html>
  • 相关阅读:
    从头到尾彻底理解KMP
    [CF1220E] Tourism
    [CF446C] DZY Loves Fibonacci Numbers
    [CF1003E] Tree Constructing
    [CF1238E] Keyboard Purchase
    [CF915E] Physical Education Lessons
    [CF788B] Weird journey
    [CF1371E2] Asterism (Hard Version)
    [CF780E] Underground Lab
    [CF372C] Watching Fireworks is Fun
  • 原文地址:https://www.cnblogs.com/unclewenyuan/p/11889778.html
Copyright © 2011-2022 走看看