且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何知道文本框中的文本是否被选中?

更新时间:2023-12-04 21:49:46

以下内容将告诉您是否在所有主流浏览器的文本输入中选择了所有文本。

The following will tell you whether or not all of the text is selected within a text input in all major browsers.

示例: http://www.jsfiddle.net/9Q23E/

代码:

function isTextSelected(input) {
    if (typeof input.selectionStart == "number") {
        return input.selectionStart == 0 && input.selectionEnd == input.value.length;
    } else if (typeof document.selection != "undefined") {
        input.focus();
        return document.selection.createRange().text == input.value;
    }
}