解除文本框的焦点

我有一个基于 ajax/url 散列的登录表单的移动模板。如果用户在 iphone 上点击 iphone 键盘上的“ go”按钮,ajax 会验证/登录他们,然后在另一个 div 中加载下一页,并隐藏当前的登录表单 div。

问题是,在 iPhone 上,键盘仍然弹出。是否存在通过 javascript 解除文本框元素焦点的方法?

118224 次浏览

使用 blur()方法或尝试将焦点设置为另一个元素,如链接。

如果你不能很容易的访问你想要模糊的特定元素,有一个稍微粗糙的方法你可以实现“模糊所有”功能。

只需在页面的某处添加以下 HTML:

<input id="blur-hack" type="text" style="position: absolute; opacity: 0;">

然后这个 JS 会分散目前关注的焦点:

document.getElementById("blur-hack").focus();

注意,对于内联 HTML 样式,我们不能使用 display: none,否则就不能关注它。positionopacity将充分地从流中移除元素-你也可以使用边距把它从页面上推开,等等。

.blur()不想和我做朋友的时候,我就用这个

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

这将保持滚动,而不会导致任何闪烁的元素

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 的解决方案

建立在@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是常数,因为它在函数调用的生命周期内从不更改。

您可以在 javascript 中使用 element.disable 参数。

例如:

<!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>

`

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()
}

如果你只是想模糊一些没有目标的东西,你可以在 ActiveElement上调用 blur():

document.activeElement.blur();