在JavaScript中,获取文本框(<input type="text">
或 <textarea>
)中选中的文本可以通过以下几种方法实现:
以下是一个简单的示例,展示如何获取文本框中选中的文本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Selected Text</title>
</head>
<body>
<textarea id="myTextarea" rows="4" cols="50">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</textarea>
<button onclick="getSelectedText()">Get Selected Text</button>
<script>
function getSelectedText() {
const textarea = document.getElementById('myTextarea');
if (window.getSelection) {
// 现代浏览器
const selectedText = window.getSelection().toString();
alert(selectedText);
} else if (textarea.selectionStart || textarea.selectionStart === 0) {
// IE 9 及更早版本
const startPos = textarea.selectionStart;
const endPos = textarea.selectionEnd;
const selectedText = textarea.value.substring(startPos, endPos);
alert(selectedText);
}
}
</script>
</body>
</html>
通过上述方法和注意事项,可以有效实现并处理JavaScript中获取文本框选中文本的功能。
领取专属 10元无门槛券
手把手带您无忧上云