[英]How to show datalist with javascript?
嘿,我想在单击按钮时显示特定输入的数据列表,但我找不到如何操作。
HTML
<input type="text" name="" value="" list="list" id='input'>
<datalist id='list'>
<option value="aaa">
<option value="bb">
</datalist>
<div onclick="showDataList(event,'input')">
Click
</div>
JS
function showDataList(e,id) {
document.getElementById(id).list.show()
}
我试过双焦点(),焦点()和点击()并检查哪个事件数据列表显示功能触发但无济于事。
要使用下拉菜单,使用 3rd 方库(例如 material-ui/semantic-ui)会更简单。
但是如果你想要干净的解决方案,这个默认方法可能很有用。
/* When the user clicks on the button, toggle between hiding and showing the dropdown content */ function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } // Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } }
.dropbtn { background-color: #3498DB; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropbtn:hover, .dropbtn:focus { background-color: #2980B9; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f1f1f1; min-width: 160px; overflow: auto; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown a:hover {background-color: #ddd;} .show {display: block;}
<div class="dropdown"> <button onclick="myFunction()" class="dropbtn">Dropdown</button> <div id="myDropdown" class="dropdown-content"> <a href="#aaa">aaa</a> <a href="#bb">bb</a> </div> </div>
并非所有浏览器都支持 Datalist,并且处理方式也不相同。 我建议你切换到诸如 flexselect 之类的东西: https ://rmm5t.github.io/jquery-flexselect/
这可能不会给您想要的答案,但没有适用于 datalist 的解决方案(在所有浏览器上)。 你可以破解自己的方法,让它在 Chrome 或 Firefox 上工作,但即使这样也很难做到,因为谷歌和 Mozilla 已经完全限制了不受信任的事件/触发器的使用。 在这里阅读: https : //www.chromestatus.com/features/5718803933560832 https://www.chromestatus.com/features/6461137440735232
此外 initMouseEvent 已弃用,所有其他允许您在过去创建此行为的低级方法也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.