实现点击复制功能

html

<style>
 .copy_box {
 	position:relative;
 	width:400px;
 	height:40px;
 }
 .copy_input {
 	width:100%;
 	height:100%;
 	font-size: 14px;
    padding-left: 13px;
    padding-right: 80px;
    border: 1px solid #e1e7f2;
    border-radius: 4px;
    color: #333;
 }
 .copy_button{
 	padding: 0 20px;
    height: 100%;
    background: #fff;
    position: absolute;
    right: 0;
    top: 0;
    border: 1px solid #e1e7f2;
    border-radius: 4px;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    cursor: pointer;
    font-size: 14px;
 }
 .hide {
 	position:absolute;
 	top:0;
 	left:0;
 	opacity:0;
 	z-index:-10;
 }
</style>

 <div class="copy_box">
 	<input class="copy_input" type="text" value="123" disabled>
 	<button class="copy_button">复制</button>
 	<input class="hide" type="text" >
 </div>

js

$(function () {
  // 点击复制
  $(".copy_button").click(function () {
    var text = $(this).prev().val();
    $(this).next().val(text);
    $(this).next().select();
    document.execCommand("copy");
    alert("复制成功");
  });
});

注意:

如果是输入框,可以通过 select() 方法,选中输入框的文本,然后调用 copy 命令,将文本复制到剪切板

但是 select() 方法只对 input 和 textarea 有效,对disabled属性的的input没有效果,可以在在页面中添加一个表单,把它隐藏掉,不能display:none,不然也拿不到复制的内容

非表单的复制功能

 $(".copy_btn").click(function() {
        $(".pop-success").show()
        setTimeout(function() {
            $(".pop-success").hide()
        }, 2000)
        const textElement = $(this).next()[0];
        copyText(textElement);
    });

    function copyText(element) {
        const range = document.createRange();
        range.selectNode(element);
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);

        try {
            const successful = document.execCommand('copy');
            const msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy text command was ' + msg);
        } catch (err) {
            console.error('Unable to copy text', err);
        }

        // Deselect the text
        selection.removeAllRanges();
    }```

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值