jQuery 如何聚焦div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17042431/
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
How to focus div?
提问by user1178399
Please don't throw stones at me because i'm total newbie at js and jquery. is it possible to focus a div? i just wanted to process events when div is clicked OR is focused and when we click outside the div. Something like that:
请不要向我扔石头,因为我是 js 和 jquery 的新手。是否可以聚焦一个div?我只想在单击 div 或聚焦时以及当我们在 div 外单击时处理事件。类似的东西:
HTML:
HTML:
<div id="focusedDiv"></div>
JS:
JS:
$("#focusedDiv").focus(function () {
....
});
$("#focusedDiv").focusout(function () {
....
});
Thanks in advance!
提前致谢!
回答by A. Wolff
You have to set tabindex attribute:
您必须设置 tabindex 属性:
<div id="focusedDiv" tabindex="-1"></div>
Or:
或者:
$("#focusedDiv").attr('tabindex',-1).focus(function () {
....
});
For style, you could set outline CSS property too:
对于样式,您也可以设置大纲 CSS 属性:
$("#focusedDiv").css('outline',0).attr('tabindex',-1).focus(function () {
....
});