Materialize UI下拉菜单点击内部内容关闭问题求助
I get exactly what's going on here—your dropdown search form closes the second you click into the input field, making it impossible to type anything. This happens because Materialize's dropdown component is programmed to close when it detects a click event that bubbles up outside the dropdown content area, and the input's click event is accidentally triggering that close logic.
Here's how to fix this issue:
1. Update Dropdown Initialization (Simplest Fix)
The easiest solution is to add the stopPropagation: true option when initializing your dropdown. This tells Materialize to ignore click events that originate inside the dropdown content, so clicking the input won't trigger the close action.
Replace your existing JavaScript code with this:
$('.dropdown-button').dropdown({ stopPropagation: true });
2. Alternative: Targeted Event Bubbling Prevention
If you want a more focused fix, you can specifically stop the click event from bubbling up from the search input alone. Add this extra snippet to your JavaScript:
$('#s').on('click', function(e) { e.stopPropagation(); });
Full Working Code Example
Here's the complete modified code with the first fix applied, ready to use:
HTML
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script> <a href="#" data-activates="search-area" class="search-header dropdown-button"><i class="material-icons">search</i></a> <div id="search-area" class="dropdown-content search-area"> <form method="get" id="searchform" action="/"> <div class="input-field"> <input class="search" type="text" name="s" id="s" value="" placeholder="Search..." /> <label class="label-icon" for="search"><i class="search-ico material-icons">search</i></label> </div> </form> </div>
CSS
.search-area { overflow: hidden !important; width: 400px !important; height: 100%; top: 4.2em !important; } .search { font-size: 16px !important; font-weight: 300; padding: 0 50px 0 0 !important; box-shadow: inset 0 0 10px -1px #e0e0e0 !important; cursor: default; } .search-header { float: left; } .search-ico { padding: 0px 10px 0 10px; background-color: #0063a3; margin: -13px 0px 0 0; } .input-field input[type="search"]+label { right: 1rem; }
JavaScript
$('.dropdown-button').dropdown({ stopPropagation: true });
With this change, the dropdown will stay open when you click into the search input, letting you type normally without any interruptions.
内容的提问来源于stack exchange,提问作者jackson

