Javascript文本字段值关注

Javascript文本字段值关注,javascript,html,css,focus,onblur,Javascript,Html,Css,Focus,Onblur,环境: 请使用IE进行测试 要求: 我有一条警告消息,检查用户输入的值是否小于8位-用户将无法移动到下一个字段…他应该保持在同一个字段上 问题: 除了一件事之外,该功能一切正常——当用户在文本字段中输入少于8位的任何值时,其返回FOUC的方式是光标移到输入值的第一个字母,而它应该移回输入值的最后一个字母 代码: <html> <body> <script> function checkField(field) { if (field.valu

环境: 请使用IE进行测试

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

问题: 除了一件事之外,该功能一切正常——当用户在文本字段中输入少于8位的任何值时,其返回FOUC的方式是光标移到输入值的第一个字母,而它应该移回输入值的最后一个字母

代码:

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

函数检查字段(字段){
如果(field.value.length<8){
//在下一次模糊后关闭并重新打开活动元素的模糊
var active=document.activeElement;
如果(活动和活动!==字段){
var blur=active.onblur | | function(){};
active.onblur=function(){active.onblur=blur};
}
field.focus();
警报(“不能少于8位”);
} 
}


这是一个黑客攻击,但这是可行的-添加一个onfocus侦听器以自身替换该值,IE将通过将光标放在末尾来操作-
onfocus=“this.value=this.value;”“

这样使用:

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

我要做的一个更改是在这之后。scrollTop=。。。dothis.scrollLeft=this.scrollWidth;否则,您无法始终看到光标。
// 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);