【问题标题】:I don't want to focusout if user is focused on particular div如果用户专注于特定的 div,我不想关注
【发布时间】:2016-08-04 04:17:28
【问题描述】:

我正在使用 focusin() 函数将 div 动态附加到正在聚焦的输入框下方。现在,当用户关注焦点时,我删除了动态附加的 div,但问题是如果用户关注该 div,我想阻止该 div 自行删除。

我的代码:

$('.ok').focusin(function() {
  $('.ok').after('<div class="thisdiv" tabindex="1">Okay Okay Okay</div>');
});

$('.ok').focusout(function() {
  if (!$('.thisdiv').is(':focus')) {
    $('.thisdiv').remove();
  }
});
.thisdiv {
  background: red;
  border: 2px dashed;
  width: 400px;
  padding: 50px;
}
.thisdiv:hover,
.thisdiv:active,
.thisdiv:focus {
  display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="ok">

JSFiddle:https://jsfiddle.net/hq5dy61j/4/

【问题讨论】:

    标签: jquery focus focusout


    【解决方案1】:

    您可以向动态 div 添加一个事件处理程序,以防止在单击该 div 时更改焦点。当通过按 TAB 更改焦点时,这将无济于事,这可能是可取的,也可能不是可取的。

    这样做的一个效果是动态 div 中的文本不能用鼠标选择。如果您想要这种行为,您可能需要考虑切换到基于类的解决方案,这样您就可以更好地控制状态更改。

    $('.ok').focusin(function() {
      var $this = $(this),
        $div = $('<div class="thisdiv" >Okay Okay Okay</div>');
    
      $div.on('mousedown', function(e){
          e.preventDefault();
      });
      $this.after($div);
    });
    
    $('.ok').focusout(function() {
        $('.thisdiv').remove();
    });
    .thisdiv {
      background: red;
      border: 2px dashed;
      width: 400px;
      padding: 50px;
    }
    .thisdiv:hover,
    .thisdiv:active,
    .thisdiv:focus {
      display: block !important;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" class="ok">

    【讨论】:

    • 你说得对,我现在正在使用基于类的解决方案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多