有没有办法使用JavaScript来*不*专注于任何HTML元素?

时间:2016-08-10 22:40:34

标签: javascript android html mobile

我有一个移动注册表单,其中包含用户的用户名,密码和密码确认字段的HTML输入元素。由于这是一个移动网络应用程序,我正在努力节省屏幕空间,我选择放弃将HTML标签放在每个元素上方,而是使用占位符属性来指示每个字段中输入的内容:。

<input id="id_username" placeholder="Choose a username" type="text" />                
<input id="id_password1" name="password1" placeholder="Choose a password" type="password" />
<input id="id_password2" name="password2" placeholder="Confirm password" type="password" />

最初我添加了一些JavaScript,以便在用户到达页面时将焦点放在用户名字段上:

<script type="text/javascript">
    document.getElementById("id_username").focus()
</script>

除了在默认Android浏览器的旧版本中,这会导致占位符消失,这很好。由于缺少占位符(和标签)可能会导致用户不清楚该字段中输入的内容,因此我将JavaScript删除了。然而,即使没有JS,我也注意到Android浏览器仍将焦点放在第一个表单字段中,这再次删除了标签。有没有什么方法可以编写页面,以便我保证没有浏览器(包括默认的Android浏览器)将重点放在这些字段中的任何一个?因为我试图将页面大小和其他请求保持在最低限度,所以不需要额外库的技术会更好。

感谢。

2 个答案:

答案 0 :(得分:0)

有时用手写一些简单的功能会更快。看看js小提琴的例子。如果你想要,可以用原生javascript替换jquery。

https://jsfiddle.net/ShinShil/y7o8mrwh/2/

var placeholder = 'enter something';
$(document).ready(function() {
  $('.placeholder').val(placeholder);
    $('.placeholder').focusin(function() {
    if($(this).val() == placeholder && $(this).hasClass('opacity')) {
      $(this).val('');
      $(this).removeClass('opacity');
    }
  });
  $('.placeholder').focusout(function() {
    if($(this).val() == '') {
        $(this).val(placeholder);
      $(this).addClass('opacity');
    }
  });
});

答案 1 :(得分:0)

如果您的控件位于表单中,则可以循环遍历所有表单中的所有控件并调用其 blur 方法:

function blurAll() {
  [].forEach.call(document.forms, function(form) {
    [].forEach.call(form.elements, function(element) {
      element.blur();
    });
  });
}
<body onload="blurAll()">
  <form>
    <input name="one" placeholder="enter something"><input name="two" placeholder="enter something">
  </form>
  <form>
    <input name="one" placeholder="enter something"><input name="two" placeholder="enter something">
  </form>
</body>

请注意,对于IE8,您需要Array.prototype.forEach的填充。

修改

也许更简单的解决方案是使用document.activeElement

function blurActive() {
  if (document.activeElement && document.activeElement.blur) {
    document.activeElement.blur();
  } 
}
<body onload="blurActive()">
  <form>
    <input name="one" placeholder="enter something"><input name="two" placeholder="enter something">
  </form>
  <form>
    <input name="one" placeholder="enter something"><input name="two" placeholder="enter something">
  </form>
 
  <p>Click on the button, then on an input to give it focus. It will be blurred in 5 seconds.</p>
  <button onclick="setTimeout(blurActive,5000);">Blur active in 5 seconds</button>
</body>