1.使用selectionStart和selectionEnd属性
可以使用JavaScript来检查文本框的selectionStart和selectionEnd属性。这些属性分别指示了当前选中文本的起始位置和结束位置。
例如,以下代码段将在用户选择文本时输出所选文本的起始位置和结束位置:
<input type="text" id="myTextbox">
var textbox = document.getElementById("myTextbox");
textbox.addEventListener("select", function() {
var selectionStart = textbox.selectionStart;
var selectionEnd = textbox.selectionEnd;
console.log("Selected text start at position " + selectionStart + " and ends at position " + selectionEnd);
});
请注意失去焦点时起始位置和结束位置不变,我们需要手动把值置0
// 监听 blur 事件
textbox.addEventListener("blur", function() {
// 将 selectionStart 和 selectionEnd 设置为 0
textbox.selectionStart = 0;
textbox.selectionEnd = 0;
});
2.使用document.getSelection()方法
还可以使用document.getSelection()方法来获取页面上任何元素中选中的文本。该方法返回一个Selection对象,其中包含有关选中文本的信息,如起始和结束位置、选中的文本、选中文本所属的DOM节点等。
var selectedText = document.getSelection().toString();
console.log("Selected text: " + selectedText);
请注意:
-
- 这种方法也适用于其他HTML元素,而不仅仅是input标签。
-
- 失去焦点时,selectedText还是有值,我们需要手动把值置空