jQuery自动补全结果横向重叠显示问题求助
Hey there! Let's work through this autocomplete display problem you're facing. It's super frustrating when the functionality works but the UI breaks—let's break down the most likely fixes:
1. Enforce Proper CSS for the Autocomplete List
First, even if you cleared other styles, jQuery UI's autocomplete relies on specific default styles that might be missing or overridden. Your partial CSS snippet only sets position: absolute—let's add the rest of the critical styles to force the list to display vertically:
/* Reset and style the autocomplete dropdown */ ul.ui-autocomplete { position: absolute; width: 100%; /* Match the width of your textarea/input */ max-width: 400px; /* Optional: set a max width if needed */ background-color: #ffffff; border: 1px solid #dddddd; border-top: none; padding: 0; margin: 0; list-style-type: none; z-index: 1000; /* Ensure it sits above other elements */ box-sizing: border-box; } /* Style individual list items */ ul.ui-autocomplete li { padding: 8px 12px; cursor: pointer; white-space: nowrap; /* Prevent text wrapping if you don't want it */ } /* Hover state for better UX */ ul.ui-autocomplete li:hover { background-color: #f5f5f5; }
Add this CSS to your stylesheet—this should override any conflicting styles and force the list to stack vertically instead of crowding horizontally.
2. Check Your Data Source Array
If the styles don't fix it, let's verify your autocomplete source. Make sure your data-autocomplete-source is returning a clean array of plain strings, not elements with extra HTML, unescaped characters, or unexpected whitespace.
For example, a valid source should look like this:
["Introduction to Biology", "Advanced Chemistry", "Physics 101"]
If your source includes HTML tags (like <span>...</span>) or weird formatting, that could throw off the layout. Use your browser's dev tools (F12) to inspect the network request or the data-autocomplete-source attribute to confirm the data is clean.
3. Verify jQuery UI CSS is Loaded
Double-check that you're including the official jQuery UI CSS file alongside the jQuery UI JS. Without the default styles, the autocomplete dropdown won't have the proper layout rules. If you're using a local setup, ensure the CSS file is linked correctly in your <head>.
4. Inspect Element Styles with Dev Tools
If none of the above works, open your browser's developer tools:
- Right-click on the broken autocomplete list and select "Inspect"
- Look at the "Styles" tab to see which CSS rules are being applied to
ul.ui-autocompleteand its<li>items - Check for unexpected properties like
display: inline,float: left, orwidth: autothat might be forcing horizontal layout
Content of this question comes from Stack Exchange, asked by Jon Golembiewski

