在JavaScript中,要复制<input>
元素中的内容,可以使用以下方法:
复制<input>
内容通常涉及到获取输入框的值,并将其复制到剪贴板。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy Input Content</title>
</head>
<body>
<input type="text" id="myInput" value="Hello, World!">
<button onclick="copyInputContent()">Copy</button>
<script>
async function copyInputContent() {
const input = document.getElementById('myInput');
try {
await navigator.clipboard.writeText(input.value);
alert('Content copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy Input Content</title>
</head>
<body>
<input type="text" id="myInput" value="Hello, World!">
<button onclick="copyInputContent()">Copy</button>
<script>
function copyInputContent() {
const input = document.getElementById('myInput');
input.select();
input.setSelectionRange(0, 99999); // For mobile devices
try {
const successful = document.execCommand('copy');
if (successful) {
alert('Content copied to clipboard');
} else {
alert('Failed to copy content');
}
} catch (err) {
console.error('Failed to copy: ', err);
}
}
</script>
</body>
</html>
通过以上方法,你可以轻松实现JavaScript中复制<input>
元素内容的功能。
领取专属 10元无门槛券
手把手带您无忧上云