【问题标题】:Javascript textfield value focus onJavascript文本字段值关注
【发布时间】:2011-07-24 03:08:43
【问题描述】:

环境: 请使用IE进行测试

要求: 我有一条警告消息,用于检查用户输入的值是否小于 8 位 - 用户将无法移动到下一个字段....他应该留在同一字段上。

问题: 除了一件事之外,功能一切都很好 - 当用户在小于 8 位的文本字段中输入任何值时,他会以这样的方式返回他的焦点,即光标移动到输入值的第一个字母,而它应该回到输入值的最后一个字母。

代码:

<html>
<body>
<script>
function checkField(field) {

        if (field.value.length < 8) {
            // Toggle the active element's blur off and back on after the next blur
            var active = document.activeElement;
            if (active && active !== field) {
                var blur = active.onblur || function(){};
                active.onblur = function(){ active.onblur = blur };
            }
            field.focus();
            alert("cannot be less than 8 digits");
        } 
    }

</script>
<input type="text" id="test1" onblur='return checkField(this);'> 
<br/>
<input type="text" id="test2" onblur='return checkField(this);'>
</tr>
</table>
</body>
</html>

【问题讨论】:

    标签: javascript html css focus onblur


    【解决方案1】:

    这是一个 hack,但这有效 - 添加一个 onfocus 侦听器以将值替换为自身,IE 会将光标放在末尾 - onfocus="this.value = this.value;":

    这样使用:

    <input id="test1" type="text" value="whatever" onblur="return checkField(this);" onfocus="this.value = this.value;" />
    

    如果您打算迁移到 JQuery(我推荐),请查看此插件:

    // jQuery plugin: PutCursorAtEnd 1.0
    // http://plugins.jquery.com/project/PutCursorAtEnd
    // by teedyay
    //
    // Puts the cursor at the end of a textbox/ textarea
    
    // codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
    (function($)
    {
        jQuery.fn.putCursorAtEnd = function()
        {
        return this.each(function()
        {
            $(this).focus()
    
            // If this function exists...
            if (this.setSelectionRange)
            {
            // ... then use it
            // (Doesn't work in IE)
    
            // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
            var len = $(this).val().length * 2;
            this.setSelectionRange(len, len);
            }
            else
            {
            // ... otherwise replace the contents with itself
            // (Doesn't work in Google Chrome)
            $(this).val($(this).val());
            }
    
            // Scroll to the bottom, in case we're in a tall textarea
            // (Necessary for Firefox and Google Chrome)
            this.scrollTop = 999999;
        });
        };
    })(jQuery);
    

    【讨论】:

    • 我要做的一个改变是在 this.scrollTop = ... do this.scrollLeft = this.scrollWidth;否则你不能总是看到光标。
    猜你喜欢
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多