JavaScript - 取消文本框的焦点

83

我有一个移动模板,其中包含一个基于ajax/url hash浏览的登录表单。如果在iphone上,用户点击iphone键盘上的“go”按钮,ajax将进行身份验证/登录,然后在另一个div中加载下一页并隐藏当前的登录表单div。

问题是,在iphone上,键盘仍然弹出。有没有办法通过javascript取消文本框元素的聚焦状态?


http://web-design.blogs.webucator.com/files/2010/08/onFocusTShirt.gif :-) 的程序设计相关内容。 - Ionică Bizău
8个回答

143

使用blur()方法,或尝试将焦点设置到其他元素(如链接)。


还有其他方法吗?我尝试将焦点设置在一个div上,但没有起作用。 - Joe
9
好的,blur() 方法是指模糊处理。 - Xint0
21
document.activeElement.blur(); 对我的情况起到了完美的作用。 - A1rPun
1
在我的情况下,我不得不使用event.target.parentNode.blur(),因为焦点更高;它甚至可以在层次结构中向上多个父级工作。以防万一有人遇到这种情况而来到这里。 - Kesarion

30

.blur()不愿意成为我的朋友时,这就是我使用的方法

function blurAll(){
 var tmp = document.createElement("input");
 document.body.appendChild(tmp);
 tmp.focus();
 document.body.removeChild(tmp);
}

2
这很棒,正是我在寻找的。我喜欢这个答案,因为它是自包含的,只做了这一件事,不留任何杂乱无用的东西。 - thomasfuchs
2
巨大的解决方案。 - user3198259
2
这是唯一一个有效的,但不幸的是它会将页面滚动到最底部。 - hyper-neutrino
我没有测试过这个,但是将 tmp.style.position = "fixed" 设置为可能会防止任何滚动。 - tobek

7
如果您只想模糊某些内容而没有特定对象,您可以在activeElement上调用blur()函数:
document.activeElement.blur();

5
你可以在Javascript中使用element.disabled参数。
例如:

<!DOCTYPE html>
<html>
<body>

Name: <input type="text" id="myText">

<p>Click the button to unfocus the text field.</p>

<button onclick="myFunction()">Unfocus input</button>

<script>
document.getElementById("myText").focus();
function myFunction() {
 
   document.getElementById("myText").disabled = true;    
    document.getElementById("myText").disabled = false;
}
</script>

</body>
</html>

`


4
如果您无法轻松访问要模糊的特定元素,那么可以使用一种有点技巧的方法来实现“全部模糊”功能。只需在页面上的某个位置添加以下HTML代码即可:
<input id="blur-hack" type="text" style="position: absolute; opacity: 0;">

然后,此JS将取消焦点当前所聚焦的任何内容:
document.getElementById("blur-hack").focus();

请注意,对于内联HTML样式,我们不能使用display: none,否则您将无法聚焦到它。 positionopacity可以足够地将元素从流中移除 - 您还可以使用边距将其推到页面之外等方法。

2
或者你可以将 height 设为 0。 - Bill

2

基于@shygoo的解决方案 - 这个方案很好地转化为TypeScript!

export function unfocus(): any {
    const tmp: HTMLInputElement => document.createElement('input');
    document.body.appendChild(tmp);
    tmp.focus();
    document.body.removeChild(tmp);
}

一些注释...

  1. 它是类型为any,这样它就与AngularJS的$timeout服务兼容,即使它实际上从未返回任何内容。
  2. tmp是常量,因为它在函数调用的生命周期内永远不会改变。

2
这将保持滚动条的位置,不会造成任何元素的闪现。
resetFocus () {
    let scrollTop = document.body.scrollTop;
    let body = document.body;

    let tmp = document.createElement('input');
    tmp.style.opacity = 0;
    body.appendChild(tmp);
    tmp.focus();
    body.removeChild(tmp);
    body.scrollTop = scrollTop;
}

基于@skygoo的解决方案。

2

我遇到了一个关于 classNames 的问题。

document.getElementsByClassName('formButtons').blur()

解决方案是使用Array.from()。

const btns = Array.from( document.getElementsByClassName('formButtons') ) 
if (btns && btns.length) {
 // go over let i in btns and 
 // btns[i].blur()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接