【H5】复制粘贴

源文案地址

使用案例

案例1:复制分享链接

function copyTextToClipboard(text) {
        var textArea = document.createElement("textarea")
        textArea.style.position = 'fixed'
        textArea.style.top = 0
        textArea.style.left = 0
        textArea.style.width = '2em'
        textArea.style.height = '2em'
        textArea.style.padding = 0
        textArea.style.border = 'none'
        textArea.style.outline = 'none'
        textArea.style.boxShadow = 'none'
        textArea.style.background = 'transparent'
        textArea.value = text
        document.body.appendChild(textArea)
        textArea.select()
        try {
            var msg = document.execCommand('copy') ? '成功' : '失败';
            console.log('复制内容 ' + msg)
        } catch (err) {
            console.log('不能使用这种方法复制内容')
        }
        document.body.removeChild(textArea)
    }

  调用:

  <div class="share"><a href="prodetail.html"></a></div>

$('.share a').on('click',function(e){
   var linkHref="http://"+document.domain+"/"+$(this).attr('href');
   copyTextToClipboard(linkHref);
   var tip = document.execCommand('copy') ? '成功' : '失败';
   layui.use( 'layer', function() {
      var layer = layui.layer;
      layer.msg('复制' + tip)
   });
   return false;
})

//与原例不同的是 添加了返回结果tip用layer提示

原文地址:https://www.cnblogs.com/smilexumu/p/8391508.html