如何使用输入框作为Bootstrap 4下拉菜单的切换开关

3
我的问题是 这个问题 的变体。
我想使用一个输入框来切换下拉菜单,而不是一个按钮。但是问题是,如果没有额外的代码,当通过 tab 键进入输入框时,下拉菜单不会打开。可以通过 focusin 事件捕获此情况。
我找到了一个可行的解决方案(如下所示),但它有点古怪,因为它在单击时打开-关闭-重新打开下拉菜单,尽管我看不到明显的闪烁。
现在,首先点击编辑控件会触发 focusin 事件,然后是 click 事件。与其他问题一样,我尝试通过调用 e.stopPropagation()e.preventDefault() 和从事件处理程序中返回 false 来阻止 bootstrap 在单击时打开下拉菜单;但什么都没用。效果是下拉菜单迅速闪烁并立即消失。从 #msg 文本中可以看出,单击首先触发 focusin,然后是 click 事件。
有什么建议吗?
一个想法是在 focusin 事件期间触发 click,但现在这意味着在物理点击时,click 事件会被触发两次,并且下拉菜单会闪烁。我也不确定还会有什么其他负面影响。

HTML(简化以便阅读):

<div class="ml-4">
  <input type="text" class="form-control" id="Medium" name="Medium" placeholder="Medium" value="">
</div>
<div class="ml-4 dropdown">
  <input type="text" class="form-control" id="Material" name="Material" placeholder="Material" value="" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
  <div class="dropdown-menu" aria-labelledby="Material">
    <button class="dropdown-item" type="button">Action</button>
    <button class="dropdown-item" type="button">Another action</button>
    <button class="dropdown-item" type="button">Something else here</button>
  </div>
</div>
<div class="ml-4">
 <div style="height:200px;"></div>
 <input type="text" class="form-control" id="Dummy" name="Dummy" placeholder="Dummy" value="">
 <p id="msg">S</p>
</div>

JS工作(与#msg有关的代码用于调试):

$("#Material").focusin(function(e) {
 $("#msg").text($("#msg").text() + '-i');
 $(this).dropdown('toggle');
});
$("#Material").click(function(e) {
 $("#msg").text($("#msg").text() + '-c');
 // when removing the following line, neither e.stopPropagation(), e.preventDefault(), nor returning false helps
 $(this).dropdown('toggle');
});
$("#Material").focusout(function(e) {
 $("#msg").text($("#msg").text() + '-o');
});
1个回答

1
我可能已经找到了一个解决方案:将 input 放在一个 div 中,触发父级 input 上的下拉菜单,并阻止 click 事件传播。
HTML:
<input type="text" class="form-control" id="Material" name="Material" placeholder="Material" value="" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

变成

<div data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
   <input type="text" class="form-control" id="Material" name="Material" placeholder="Material" value="">
</div>

JS:(仅更改的部分)

$("#Material").focusin(function(e) {
 $("#msg").text($("#msg").text() + '-i');
 $(this).parent().dropdown('toggle');
});
$("#Material").click(function(e) {
 e.stopPropagation();
 $("#msg").text($("#msg").text() + '-c');
});

这个解决方案似乎工作得很好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接