Javascript 文本字段值关注

标签 javascript html css focus onblur

环境: 请使用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>

最佳答案

这是一个 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);

关于Javascript 文本字段值关注,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6804702/

相关文章:

javascript - 如果另一个 div 的高度大于值(使用 jquery),则移动一个 div

javascript - WebAssembly 实例 : Javascript behavior when calling exported functions

javascript - CSS Div 2 背景颜色

CSS 搜索框如何保持响应

javascript - Monaco Editor 的高度

javascript - 防止在自定义日期选择器中手动输入

javascript - 当查询找不到用户时,为什么页面不重定向?

javascript - 如何完全替换 HTML 元素上的数据对象

css - 字体无法在 Safari 或移动浏览器中呈现

javascript - 在页面加载时将 CSS id 淡入另一个