如何知道文本框中的文本是否被选中? [英] How to know if the text in a textbox is selected?

查看:2067
本文介绍了如何知道文本框中的文本是否被选中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有文本框< input type ='text'> 只允许使用数字字符,并且不会让用户多次输入点(。)。问题是,如果选中文本框中的文本,用户打算用点覆盖内容,从而允许它!问题是,如何在javascript中判断该文本框中的文本是否被选中。

I have text boxes <input type='text'> that only allow numeric characters and wont let the user enter a dot (.) more than once. Problem is, if the text in the text box is selected, the user intends to overwrite the contents with a dot, hence making it allowed! The question is, how can you tell in javascript whether the text in that text box is selected or not.

谢谢

推荐答案

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

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;
    }
}

这篇关于如何知道文本框中的文本是否被选中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆