原生js复制内容至剪切板,无需任何插件

获取html输入标签内容,聚焦,然后执行copy命令:document.execCommand(‘copy’)。

示例完整代码:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js剪切板-www.cpury.com</title>
</head>
<body>
    <textarea type="text" id="demo" rows="10" cols="30"></textarea><br/><br/>

    <button onclick="copy()">点击复制</button>

    <script type="text/javascript">
    	function copy() {
    		var ele = document.getElementById("demo");
    		ele.focus();
    		ele.setSelectionRange(0, ele.value.length);
    		document.execCommand('copy');
    	}
    </script>
</body>

(版权归cpury.com所有,转载请注明出处。)