JavaScript(或jQuery)中是否有“焦点”? [英] Is there a 'has focus' in JavaScript (or jQuery)?
本文介绍了JavaScript(或jQuery)中是否有“焦点”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以做这样的事情(通过插件改编)
Is there something I can do like this (perhap via a plugin)
if ( ! $('form#contact input]').hasFocus()) {
$('form#contact input:first]').focus();
}
基本上,将焦点设置为第一个输入,但仅限于用户没有已经点击了什么?
Basically, set focus to the first input, but only if the user has not already clicked into anything?
我知道这也会有用,但还有更优雅吗?
I know this will work too, but is there anything more elegant?
$(function() {
var focused = false;
$('form#contact input]').focus(function() {
focused = true;
});
setTimeout(function() {
if ( ! focused) {
$('form#contact input:first]').focus();
}
}, 500);
});
推荐答案
没有原生解决方案但是还有更多优雅的方式你可以做到:
There is no native solution but yes there is a more elegant way you can do it:
jQuery.extend(jQuery.expr[':'], {
focus: "a == document.activeElement"
});
您正在定义一个新的选择器。请参阅插件/创作。然后你可以这样做:
You're defining a new selector. See Plugins/Authoring. Then you can do:
if ($("...").is(":focus")) {
...
}
或:
$("input:focus").doStuff();
这篇关于JavaScript(或jQuery)中是否有“焦点”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文