Javascript 是否可以在页面加载时从文本输入中移除焦点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4276754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to remove the focus from a text input when a page loads?
提问by Exitos
I have a site with one textfield for search however I dont want the focus to be on it when the page loads however it is the only text input on the form, is it possible to remove the focus?
我有一个带有一个用于搜索的文本字段的站点,但是我不希望在页面加载时将焦点放在它上面,但它是表单上唯一的文本输入,是否可以移除焦点?
回答by Coin_op
A jQuery solution would be something like:
jQuery 解决方案类似于:
$(function () {
$('input').blur();
});
回答by Gabriele Petrioli
use document.activeElement.blur();
用 document.activeElement.blur();
example at http://jsfiddle.net/vGGdV/5/that shows the currently focused element as well.
http://jsfiddle.net/vGGdV/5/上的示例也显示了当前聚焦的元素。
Keep a note though that calling blur()
on the body element in IE will make the IE lose focus
请注意,blur()
在 IE中调用body 元素会使 IE 失去焦点
回答by jammus
You can use the .blur()
method. See http://api.jquery.com/blur/
您可以使用该.blur()
方法。见http://api.jquery.com/blur/
回答by Shadow Wizard is Ear For You
$(function() {
$("#MyTextBox").blur();
});
回答by Ivan
I would add that HTMLElementhas a built-in .blur
method as well.
我想补充一点,HTMLElement也有一个内置.blur
方法。
Here's a demo using both .focus
and .blur
which work in similar ways.
这是一个使用两者的演示.focus
,.blur
它们以类似的方式工作。
const input = document.querySelector("#myInput");
<input id="myInput" value="Some Input">
<button type="button" onclick="input.focus()">Focus</button>
<button type="button" onclick="input.blur()">Lose focus</button>