防止某些元素受到关注 [英] Prevent certain elements from receiving focus
问题描述
$ mobileMenu
或 $ menuItems
中,则允许它移除焦点: var $ body = $(body);
var $ mobileMenu = $(#mobile-menu);
var $ menuItems = $(#main-menu a);
$ body.on(focus.spf,*,function(e){
e.stopPropagation();
$ this = $(this);
//防止物品接收焦点并切换视图
if(!$ this.is($ mobileMenu)&&!$ this.is($ menuItems)){
$ this.blur();
} else {
console.log(this);
}
})
我遇到的问题是,如果现在不可聚焦的通常可聚焦的元素位于我的任何白名单之前,这可以防止用户专注于任何事情元素,因为它只是试图重新集中在同一个元素上。
有人知道我可以告诉它跳到下一个可聚焦元素吗?
此作品(已更新):
< code $ body.on(focus.spt,*,function(e){
$ this = $(this);
if(!$ this.is($ mobileMenu)&&!$ this.is($ menuItems)){
$ this.blur();
var next = $ this.nextAll()。find('a,input') ;
if(next.length> 0)next [0] .focus();
} else {
console.log('ok',this);
e。 stopPropagation();
}
})
(更新)小提琴 - > http://jsfiddle.net/CADjc/
您可以看到在控制台中哪些元素接收焦点(主菜单a
和手机菜单
)
测试:
< input type =texttabindex =1value = 测试 >
< span>< input type =texttabindex =2value =test>< / span>
< div>< input type =textid =mobile-menutabindex =3value =mobile-menu>< / div>
< div>< span>
< div id =main-menu>
< a tabindex =4>主菜单< / a>
< a tabindex =5>主菜单< / a>
< / div>
< / span>< / div>
< span>
< input type =texttabindex =6value =test>
< / span>
So I have the following function. What it does is listens for the focus event on all elements. If that element is either in $mobileMenu
or $menuItems
it permits it otherwise it removes the focus:
var $body = $("body");
var $mobileMenu = $("#mobile-menu");
var $menuItems = $("#main-menu a");
$body.on("focus.spf", "*", function(e){
e.stopPropagation();
$this = $(this);
// Prevent items from recieving focus and switching view
if (!$this.is($mobileMenu) && !$this.is($menuItems)) {
$this.blur();
} else {
console.log(this);
}
})
The issue I have is that this prevents the user from focusing on anything whatsoever if a normally focusable element that is now non-focusable precedes any of my white-listed elements as it just attempts to refocus on the same element over and over again.
Does anyone know how I can tell it to instead skip to the next focusable element?
This works (updated) :
$body.on("focus.spt", "*", function(e){
$this = $(this);
if (!$this.is($mobileMenu) && !$this.is($menuItems)) {
$this.blur();
var next=$this.nextAll().find('a,input');
if (next.length>0) next[0].focus();
} else {
console.log('ok',this);
e.stopPropagation();
}
})
(updated) fiddle -> http://jsfiddle.net/CADjc/
You can see in the console which elements that receives focus (main-menu a
and mobile-menu
)
Tested on :
<input type="text" tabindex="1" value="test">
<span><input type="text" tabindex="2" value="test"></span>
<div><input type="text" id="mobile-menu" tabindex="3" value="mobile-menu"></div>
<div><span>
<div id="main-menu">
<a tabindex="4">main-menu</a>
<a tabindex="5">main-menu</a>
</div>
</span></div>
<span>
<input type="text" tabindex="6" value="test">
</span>
这篇关于防止某些元素受到关注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!