How to allow keyboard tab focusing on div

≯℡__Kan透↙ 提交于 2019-12-23 13:22:10

问题


I made a message box on which there are two buttons on it. Basically it's a jQuery plugin, that popup with the overlay effect. But when message box appears, and user press the tab button then the message dialog do not focus. So how can i do it then if my message box appear, then focus go to my message box automatically? and when focus lose and user press the tab button again then it again comeback to my message dialig If i click on the message box with the mouse and then press the tab button, then the focus comes to button and then gone. Here is the image

. Here is the code that make the box.
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()

Thanks


回答1:


You can't set focus on div. You should catch "Tab" key press event and set focus on "Yes" button manually. If "Yes" button already has focus, then you should focus "No" button.

$('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();
      }
    }
  } 
});



回答2:


tabindex is a thing for divs. Set it to zero and native HTML5 will insert the correct tabindex. Remember, all lower case:

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

This will allow you to focus the div with the keyboard.

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

// select it with

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

// or with smelly jQuery

$([autofocus]).focus();

If you're using jQuery, you can find the focused div easily with:

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

Then do things, like .click():

$focused.click()

This will click that thing.



来源:https://stackoverflow.com/questions/10227038/how-to-allow-keyboard-tab-focusing-on-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!