点击按钮 复制一个字段 如果用input 不要随意hidden

这里有段代码点击按钮 复制input中的内容,但是在项目中不太适合我。

于是我参考了:https://www.jianshu.com/p/13442dc61e06

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    <textarea id="copy"></textarea>
    <div class="wrap">
      <p id="content">楼观岳阳尽,川迥洞庭开。雁引愁心去,山衔好月来。</p><br />
      <button id="btn">拷贝</button>
    </div>

    <script type="text/javascript">
      //处理按钮点击事件
      var btn = document.getElementById('btn');
      btn.onclick = function(){
        //获取p节点的文本
        var ctnt = document.getElementById('content').innerText;
        //为textarea的value赋值
        var copy = document.getElementById('copy');
        copy.value = ctnt;
        //调用选中,执行复制命令
        copy.select();
        document.execCommand('copy');
        //提示成功
        alert('拷贝成功!');
      }
    </script>

实现原理,是使用一个textarea或者input标签,调用标签自带的select()方法,再调用浏览器的copy命令。

textarea 也可以改成是input,我改成了input,然后我需要在页面隐藏input,但是这个有个问题。

如果你直接隐藏,可能会导致无法复制到内容。

我在input里面加了

1
style="display:none"

发现没办法复制到内容。

参考1:https://www.cnblogs.com/minigrasshopper/p/8967339.html

参考2:https://blog.csdn.net/qq_39657769/article/details/120651015

最后我也为了省点事,直接加了个

1
style="position: fixed;z-index: -100;font-size: 10px;width: 10px;height: 5px;overflow: hidden"

此文希望给你带来感觉!快感那种

此文章的评论已关闭.