我正在尝试使用javascript复制p标签的所有内容。它可以工作,但是可以将文本复制成一长行。我希望它使用break标签以这种格式复制,就像有人用鼠标复制/粘贴一样:
当前时间: :
发现时间:
环境温度°C
笔记:
频率:
可重现?”
非常感谢您的帮助。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<h2>Documentation Sheet</h2>
<p id="p1">
Current Time: :<br>
Time Found: :<br>
Ambient Temp: °C<br>
<br>
<br>
Notes:
<br>
<br>
Frequency:<br>
Reproducible?
</p>
<button onclick="copyToClipboard('#p1')">Copy text</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</body>
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
</html>ere
最佳答案
可以编写一个函数来做到这一点,例如:
function copyToClipboard(id) {
var from = document.getElementById(id);
var range = document.createRange();
window.getSelection().removeAllRanges();
range.selectNode(from);
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
注意:我的解决方案不需要jQuery,并且将文档ID作为输入,所以不要忘记省略“#”!
只需按以下方式使用它:
<button onClick="copyToClipboard('p1')">Copy text</button>