jsvascript 点击复制

 余温
2018年09月01日 15时40分
 web

主要就是这个方法

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)
    }


这个复制过去就可以测试了

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>点击复制</title>
    <link rel="stylesheet" href="">
</head>

<body>
    <script type="text/javascript">

    // 点击的时候调用 copyTextToClipboard() 方法就好了.
    function copyUrl2 () {
    	let text = document.querySelector('#text').value;
    	let cont;
    	 text == ''? cont='复制的内容':cont=text
      copyTextToClipboard(cont)
    }

    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)
    }
    </script>
    </script>
    <input type="text"  id="text" value="" placeholder="这里写要复制的内容" /><br/>
    <input type="button" onClick="copyUrl2()" value="点击复制代码" /><br/>
    <textarea cols="20" rows="10" id="biao1" placeholder="复制在这里试试"></textarea>
</body>

</html>

放个血小板就算完了

工作细胞 - 2.jpg

{{vo.nickname}}:{{vo.content}}

{{vo.time}} 回复


  • {{level.nickname}} 回复 {{level.father_nickname}}{{level.content}}
  • {{level.time}} 回复


@
登陆后评论