twitter-bootstrap - 如何使用输入字段作为引导程序 4 下拉菜单的切换
问题描述
我的问题是另一个问题的变体
我想使用输入字段来切换下拉菜单,而不是按钮。问题是,如果没有额外的代码,下拉菜单在输入时不会打开。这可以通过 focusin 事件捕获。
我找到了一个可行的解决方案(如下所示),但它有点古怪,因为它在单击时打开-关闭-打开下拉列表,尽管我没有看到可见的闪烁。
现在,单击编辑控件首先触发 focusin 事件,然后触发 click 事件。在另一个问题中,我尝试通过调用来阻止引导程序打开下拉菜单e.stopPropagation()
,e.preventDefault()
并从事件处理程序返回 false;没有任何效果。效果是下拉菜单快速闪烁并立即消失。从#msg
文中可以看出,点击先触发focusin,然后触发点击事件。
有什么建议么?
一个想法是在 focusin 事件期间触发点击,但现在这意味着在物理点击时点击事件会被触发两次并且下拉菜单会闪烁。我也不确定可能产生的其他不良副作用。
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');
});
解决方案
我可能已经找到了一个解决方案:将input
a包装起来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');
});
这个解决方案似乎工作正常。
推荐阅读
- c# - 多人数据最佳实践
- sql - spark.sql 无法执行基本的 SQL 调用。FROM 上的问题
- javascript - 从对象数组中,如果对象的 valueA 与变量匹配,如何获取对象的 valueB?
- javascript - Hammer js嵌套事件?
- java - Java多线程mysql插入
- java - Spring Boot Mixpanel:如何将属性设置为用户配置文件?
- xamarin.forms - Xamarin 为 RootviewController 构建 IOS 应用程序
- python - 在 Python 中使用递归生成序列
- python - Postgresql Json 列不保存 utf-8 字符
- java - 在 OSX 和 ojdbc 上使用 JHipster 编译错误;有没有人遇到过这个问题并通过了它?