如何允许键盘Tab键聚焦于div元素

8
我在消息框上放置了两个按钮。基本上,这是一个jQuery插件,它具有覆盖效果。但是当消息框出现时,用户按下tab键时,消息对话框不会获得焦点。那么,如果我的消息框出现,如何使焦点自动转到我的消息框?当焦点失去并且用户再次按下tab键时,它会再次回到我的消息对话框。如果我用鼠标单击消息框,然后按下tab键,则焦点移到按钮,然后消失。以下是制作框的代码:enter image description here。请问如何解决这个问题?
var containerDiv = $("<div></div>", {
    id: config.containerDivID   
}); 

// append all the div to main Div(container)
containerDiv.append(messageDiv, buttonDiv);

centerPopup(config, containerDiv);
loadPopup(config);

function centerPopup(config, container){
    var backgroundPopup = $("<div></div>", {
        id: "backgroundPopup"
    }); //end of  imageDiv   
    $("body").append(backgroundPopup);
    $("body").append(container);
    $("#backgroundPopup").css({
        "height": windowHeight
    });
} //end of  centerPopup()

function loadPopup(config){
    //loads popup only if it is disabled
    if(popupStatus==0){
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("slow");
        $("#" + config.containerDivID).fadeIn("slow");
        popupStatus = 1;
   }  //end of if
} //end of function loadPopup()

谢谢


我不知道你是否可以将焦点设置到 DIV 上。为什么不将焦点设置到“是/否”按钮上呢?按钮可以接受焦点。 - Muhammad Alvin
是的,我想说的是,当你按下标签按钮时,按钮应该获得焦点。在消息 div 上设置焦点有什么作用?我希望当你按下 Tab 键时,按钮能够获得焦点。谢谢。 - Basit
2个回答

22

tabindex是 div 元素的一个属性。将其设置为零,原生HTML5将会插入正确的tabindex。请记住,所有字母都是小写:

<div tabindex=0> Stuff Here </div>

这样可以让你使用键盘聚焦到该div元素。

<div tabindex=0, autofocus=true> Stuff Here </div>

// select it with

document.querySelector("[autofocus]").focus();

// or with smelly jQuery

$([autofocus]).focus();

如果您正在使用jQuery,您可以轻松找到具有焦点的div

var $focused = $(':focus');

那么就可以执行像是.click()这样的操作:

$focused.click()

这将点击那个东西。


-2

你不能将焦点设置在 div 上。

你应该捕获 Tab 键按下事件,并手动设置焦点在 Yes 按钮上。

如果 Yes 按钮已经有焦点,则应将焦点聚焦到 No 按钮上。

$('body').live('keydown', function(e) { 
  if (is_dialog_visible) {
    var keyCode = e.keyCode || e.which; 
    if (keyCode == 9) { 
      e.preventDefault(); 
      if (container.find(".yes").is(":focus")) {
        container.find(".no").focus();
      } else {
        container.find(".yes").focus();
      }
    }
  } 
});

KeyboardEvent.keyCode已被弃用,请使用KeyboardEvent.key代替:KeyboardEvent.key === "Tab" - Константин Ван

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接