如何使 HTML 选择下拉列表在模糊时关闭



嗨,我需要我的下拉列表框在它们失焦或用户将鼠标悬停在除它之外的任何其他 html 元素上时关闭。如何实现这一点?

我可以想到一个模糊事件,有没有更好的方法来处理这个问题?

好问题,但这仅适用于 FF,因为 IE 和 Chrome 无法识别针对option元素的事件:(

)实现这一点的一种方法是为option元素设置一个timeout,一旦我们mouseleave它就会触发。如果为树中的另一个option注册了新mouseenter,我们只需清除超时,否则.blur()页面上的任何select*。

现场演示

var blurSelectTimeout;
function blurSelect(){
   blurSelectTimeout = setTimeout(function(){
       $('select').blur();
   },200);
}
$('select').mouseleave(blurSelect).find('option').hover(function(e){
  if(e.type=='mouseenter') clearTimeout(blurSelectTimeout);
  else blurSelect();
});
  • 有趣的是,$(this).parent('select').blur();行不通,所以这是我最好的尝试。

最新更新