防止焦点离开表单字段

时间:2013-05-18 20:24:23

标签: javascript html cordova

在我的应用中,我有一个像这样的登录表单

<div id="container">
  <form name="login" id="login" method="post" action="">
    <input name="email" type="text" class="label" id="email" placeholder="Enter email...">
    <input name="password" type="password" class="label" id="password" placeholder="Enter password...">
    <input type="submit" name="submit" id="submit" value="Login">
    <a href="register.html" class="sign">Sign Up</a>
  </form>
</div>

在触摸设备上,当我点击屏幕时,焦点会离开表单域(输入,按钮,链接)。这种情况发生在黑莓和Android设备上,没有在iphone上试过。

如何防止焦点离开表单字段?我正在使用phonegap构建应用程序。

2 个答案:

答案 0 :(得分:1)

我认为您不能阻止用户点击/选择其他内容,但只要丢失它就可以返回焦点。最简单的情况:

<input onblur="this.focus()" type="text" name="text1"/>

但是你可以永久地将用户锁定到该输入中,除非用一个函数替换它,该函数评估当前输入是否由于某种原因仍需要焦点,否则不会再次触发焦点。

如果您的问题是当用户这样做以滚动页面时,您可以尝试这样的事情:

<script type="text/javascript">
    var last_selected_input;
    window.onscroll = function () {
        if (last_selected_input) {
            last_selected_input.focus();
        }
    }
</script>

<input type="text" name="text1" onfocus="last_selected_input = this" />

但是,只要字段完成,您就需要清除变量last_selected_focus,以避免持续关注每个页面滚动。

答案 1 :(得分:0)

可以像保持当前输入选择的变量一样简单。

$(document).ready(function () {
    var selected;
    $('input').focus(function (e){
       selected = $(this).attr('id');
    });
    $('window').blur(function() {
       $('#selected').focus();
    });
});