我有一个带有登录表单的移动模板,该表单是基于ajax / url哈希的浏览。如果在iphone上用户点击iphone键盘上的“go”按钮,ajax会对其进行身份验证/登录,然后将下一页加载到另一个div中,并隐藏当前的登录表单div。
问题是,在iphone上键盘仍然弹出。无论如何通过javascript取消对文本框元素的聚焦?
答案 0 :(得分:62)
使用blur()
方法或尝试将焦点设置在链接等其他元素上。
答案 1 :(得分:15)
这是我在.blur()
不想成为我的朋友时使用的
function blurAll(){
var tmp = document.createElement("input");
document.body.appendChild(tmp);
tmp.focus();
document.body.removeChild(tmp);
}
答案 2 :(得分:3)
如果您无法轻松访问要模糊的特定元素,则可以采用一种轻微的方法来实现“全部模糊”功能。
只需在页面上的某处添加以下HTML:
<input id="blur-hack" type="text" style="position: absolute; opacity: 0;">
然后这个JS将把目前关注的任何事情都集中在一起:
document.getElementById("blur-hack").focus();
请注意,对于内联HTML样式,我们无法执行display: none
,否则您无法专注于它。 position
和opacity
将充分删除流中的元素 - 您还可以使用边距将其推离页面等。
答案 3 :(得分:1)
基于@shygoo的解决方案 - 这可以很好地转换为TypeScript!
export function unfocus(): any {
const tmp: HTMLInputElement => document.createElement('input');
document.body.appendChild(tmp);
tmp.focus();
document.body.removeChild(tmp);
}
一些说明......
any
,因此它与AngularJS的$timeout
服务兼容,即使它实际上从未返回任何内容。tmp
是常量,因为它在函数调用的生命周期内永远不会改变。答案 4 :(得分:0)
这将保持滚动,而不会导致任何元素闪烁
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的解决方案
答案 5 :(得分:0)
您可以在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>
`
答案 6 :(得分:0)
我在 classNames
上遇到问题document.getElementsByClassName('formButtons').blur()
和 solution 是Array.from()
const btns = Array.from( document.getElementsByClassName('formButtons') )
if (btns && btns.length) {
// go over let i in btns and
// btns[i].blur()
}
答案 7 :(得分:0)
如果你只想模糊没有目标的东西,你可以在activeElement上调用blur()
:
document.activeElement.blur();