Bootstrap datepicker选择后返回焦点

如果使用autoclose: true 从eternicode初始化引导日期选取器,则会发生两种不良行为:

  1. 选择器关闭后,当您切换到下一个字段时,您将再次从文档的开头开始。 这在长forms上可能非常麻烦。
  2. 由于选择器以编程方式更改值,因此任何关注输入上的blur事件的侦听器都将无法正常运行。 当您选择选择器值并且输入值未更改时,实际上会出现模糊。 然后bootstrap-datepicker以编程方式更新该字段,因此永远不会使用新值触发模糊。

这是堆栈片段中的演示
*选择任何字段,从选择器中选择一个值,然后单击Tab

 $(".datepicker").datepicker({ autoclose: true }); 
      


根据选择jQuery UI datepicker后对Focus字段的回答,您可以使用onCloseonSelect事件,但bootstrap选择器不提供这些事件 。

简单地用hide替换它们似乎也不起作用,因为重新聚焦将创建一个无限循环,在您尝试关闭它时始终保持选择器打开。

 $(".datepicker").datepicker({ autoclose: true }) .on('hide', function () { $(this).focus(); }); 

Stack Snippet演示

 $(".datepicker").datepicker({ autoclose: true }) .on('hide', function () { $(this).focus(); }); 
      


这是一个黑客工作,但你可以有条件地隐藏和显示元素,以避免无限循环。 在隐藏时,检查这是否是第一次尝试隐藏。 如果输入没有焦点(意味着他们已经使用了下拉菜单并且我们丢失了Tab键顺序,那么重新聚焦将导致选择器显示。我们也将捕获此节目并从那里隐藏,返回到我们的原始代码我们会在物体上来回传递属性,以便我们可以管理状态。

这将是这样的:

 $(".datepicker").datepicker({ autoclose: true }) .on('hide', function () { if (!this.firstHide) { if (!$(this).is(":focus")) { this.firstHide = true; // this will inadvertently call show (we're trying to hide!) this.focus(); } } else { this.firstHide = false; } }) .on('show', function () { if (this.firstHide) { // careful, we have an infinite loop! $(this).datepicker('hide'); } }) 

Stack Snippet演示

 $(".datepicker").datepicker({ autoclose: true }) .on('hide', function () { if (!this.firstHide) { if (!$(this).is(":focus")) { this.firstHide = true; // this will inadvertently call show (we're trying to hide!) this.focus(); } } else { this.firstHide = false; } }) .on('show', function () { if (this.firstHide) { // careful, we have an infinite loop! $(this).datepicker('hide'); } }) 
      


使用@KyleMit解决方案添加的当前日期选定function

 var date = new Date(); var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()); var end = new Date(date.getFullYear(), date.getMonth(), date.getDate()); $(".datepicker").datepicker({ autoclose: true }) .on('hide', function () { if (!this.firstHide) { if (!$(this).is(":focus")) { this.firstHide = true; // this will inadvertently call show (we're trying to hide!) this.focus(); } } else { this.firstHide = false; } }) .on('show', function () { if (this.firstHide) { // careful, we have an infinite loop! $(this).datepicker('hide'); } }) $('.datepicker').datepicker('setDate', today); 
      


我试图达到同样的目的,但不知何故,解决方案是一个小小的车。 例如,如果再次单击相同的日期选择器,则它没有响应。 如果多次单击,浏览器将停止响应。 我有一个更好的解决方案,如下所示。

我的解决方案是欺骗datepicker专注于DIV的下一个元素。 我有欧芹validation,它自动为我添加

     
      $('.datepicker').datepicker({ autoclose: true }).on('hide', function () { $(this).next('ul').attr('tabindex',-1).focus(); });