防止用户离开输入字段

时间:2018-06-22 12:22:34

标签: javascript html5 internet-explorer

我正在尝试在前端(IE11)上进行输入字段验证。

当输入验证失败时,用户不应离开输入字段。他也不能激活页面上的其他控件。

我尝试通过使用

重新获得焦点
element.onblur = (event) => { 
$(id).focus();
}

并使用

阻止任何点击
window.onclick = (event) => {
event.preventDefault();
window.event.cancelBubble = true;
window.event.returnValue = false;
}

但是页面上仍有激活的控件(如“选项卡”和“选择框”)。

关于如何将用户限制为特定输入字段的任何想法?

1 个答案:

答案 0 :(得分:0)

您可以使用setInterval()方法。这样做:

var test = false;
var myTimer = setInterval( function() {
  if ( $( '.hello' ).val() == 'hello' ) {
    test = true;
    clearInterval( myTimer )
  } else {
    test = false;
    $( '.hello' ).focus()
  }
}, 1 )

window.onclick = function( e ) {
  if ( !test && !e.target.matches( '.hello' ) ) e.preventDefault()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>
  <a href="https://stackoverflow.com">This is a Link</a>
  <input type="checkbox" id="chk">
  <label for="chk">This is a Checkbox</label>
</p>
<p>Only valid content is: <b>hello</b><br><input type="text" class="hello"></p>