jQuery .has(“:focus”) in FF/Chrome/Safari

巧了我就是萌 提交于 2019-12-12 18:22:23

问题


I have a textbox that has filter as you type results below it. I have jQuery that detects when focus leaves the textbox so it can hide the results div. BUT I don't want to hide the results if the results are click on so that I can use that click to redirect to a different page for that item.

I'm using .has(":focus") to check if my results div or any of its children have focus. My problem is that this only works in IE as far as I can tell. Anyone know why?

$("#TextBox").blur(function () {
    if ($("#ResultsDIV").has(":focus").length == 0) {  //if you click on anything other than the results
        $("#ResultsDIV").hide();  //hide the results
    }
});

UPDATE: Thanks to Climbage I've got this working...

var resultsSelected = false;
$("#ResultsDIV").hover(
    function () { resultsSelected = true; },
    function () { resultsSelected = false; }
);
$("#TextBox").blur(function () {
    if (!resultsSelected) {  //if you click on anything other than the results
        $("#ResultsDIV").hide();  //hide the results
    }
});

Working Example: http://jsfiddle.net/cB2CN/


回答1:


The problem is that all not elements on the DOM actually accept focus, and it's up to the browser to decide which ones do. See Which HTML elements can receive focus?

Maybe have a hover event on your #ResultsDIV that sets a global variable to determine if the element has focus when you click on it.



来源:https://stackoverflow.com/questions/10391823/jquery-hasfocus-in-ff-chrome-safari

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