效果说明:
当用户鼠标点击搜索输入框,可以显示预设商品信息,移除鼠标就隐藏内容,主要的思路是修改resultList里的原display样式none为block;
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>小米搜索框显示隐藏案例</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } ul { list-style: none; } .mi { position: relative; width: 223px; margin: 100px auto; } .mi .search-text { width: 223px; height: 48px; padding: 0 10px; font-size: 14px; line-height: 48px; border: 1px solid #e0e0e0; outline: none; } /* 搜索框边框颜色 */ .mi .search { border: 1px solid #ff6700; } /* 下拉菜单 */ .result-list { position: absolute; left: 0; top: 48px; display:none; width: 223px; border: 1px solid #ff6700; border-top: 0; background: #fff; } .result-list a { padding: 6px 15px; font-size: 12px; color: #424242; text-decoration: none; } .result-list a:hover { background-color: #eee; } </style> </head> <body> <div class="mi"> <input type="search" placeholder="小米笔记本" class="search-text"> <ul class="result-list"> <li><a href="#">全部商品</a></li> <li><a href="#">小米11</a></li> <li><a href="#">小米10S</a></li> <li><a href="#">小米笔记本</a></li> <li><a href="#">小米手机</a></li> <li><a href="#">黑鲨4</a></li> <li><a href="#">空调</a></li> </ul> </div> <script> const searchText = document.querySelector('.search-text') const resultList = document.querySelector('.result-list') // resultList.style.display='none' searchText.addEventListener('focus',function(){ resultList.style.display='block' searchText.classList.add('search') }) searchText.addEventListener('blur',function(){ resultList.style.display='none' searchText.classList.remove('search') }) </script> </body> </html>