Ning Kailiang's Website Building Blog 简体中文
Baidu search box JS effect

Baidu search box JS effect:How can I implement a Baidu search box with JavaScript for a real-time search suggestion effect?

Author:Ning Kailiang's Website Building Blog · Date:20261010

This page answers the following questions about“Baidu search box JS effect”:How can I implement a Baidu search box with JavaScript for a real-time search suggestion effect?What are the key JavaScript techniques to create a Baidu search box with auto-complete and history suggestions?How do I style and animate a Baidu-like search box using JavaScript and CSS to match the original design?

Q: How can I implement a Baidu search box with JavaScript for a real-time search suggestion effect?

A: To implement a Baidu-style search box with real-time suggestions, start by creating an input field and a dropdown list container in your HTML. Use JavaScript to listen for the 'input' event on the input field. Each time the user types, capture the current value and debounce the requests to avoid overwhelming the server. Then, send an asynchronous fetch request to your backend or a search API that returns matching suggestions. For a pure front-end demo, you can use a static array of keywords and filter it based on the input. Once you receive the suggestions, dynamically render them as list items inside the dropdown. Add keyboard navigation using arrow keys to highlight items and Enter to select. Also, handle blur events to hide the dropdown when the user clicks outside. For a more Baidu-like experience, include features like highlighting the matched part of each suggestion and showing a loading spinner. Remember to sanitize user input to prevent XSS attacks. This creates a smooth, real-time search suggestion effect similar to Baidu's search box.

Q: What are the key JavaScript techniques to create a Baidu search box with auto-complete and history suggestions?

A: Creating a Baidu search box with auto-complete and history suggestions involves several key JavaScript techniques. First, use event delegation to efficiently handle clicks on dynamically generated suggestion items. Second, implement a debouncing function to limit API calls while typing, typically with a 200-300ms delay. Third, store search history in localStorage when the user submits a query, and retrieve it when the input gains focus or is empty, displaying recent searches alongside auto-complete results. Fourth, use the 'focus' event to show the dropdown with history, and the 'input' event to fetch and display auto-complete suggestions. Fifth, differentiate between history and auto-complete items with icons or labels. Sixth, handle keyboard interactions such as ArrowUp, ArrowDown, and Enter to navigate and select suggestions. Seventh, ensure the dropdown remains accessible and closes when clicking outside using a document click listener. Finally, consider performance by caching frequent queries. By combining these techniques, you can replicate Baidu's intuitive search experience, making it easy for users to find past and suggested queries quickly.

Q: How do I style and animate a Baidu-like search box using JavaScript and CSS to match the original design?

A: To style and animate a Baidu-like search box, start by mimicking Baidu's visual design: a rounded input field with a blue border on focus, a search icon inside, and a dropdown that html">appears below. Use CSS to set the input's width, height, padding, border-radius, and box-shadow. For the dropdown, html">apply absolute positioning, a white background, subtle border, and a slight shadow to make it float above other content. Use JavaScript to toggle a class that controls the dropdown's visibility with a smooth transition—for example, opacity and transform: translateY(-10px) to slide down. Add a delay or use CSS transitions for the fade-in effect. To animate individual suggestion items, html">apply hover and active states with background color changes. For keyboard navigation, highlight the selected item with a different background. You can also add a loading animation, such as a spinning icon, while fetching suggestions. Baidu uses a distinctive blue (#3385ff) for highlights; incorporate that into your active and hover states. Additionally, ensure responsiveness by adjusting widths for mobile. By carefully combining CSS transitions and JavaScript class toggling, you can achieve a polished, animated search box that closely resembles Baidu's.

Baidu search box JS effect

Dialogue about

Common scenarios of "Baidu search box JS effect"

【前端新手小李】 王哥,我想给博客加一个类似百度搜索框的那种JS效果,你能给我讲讲怎么实现吗?

【资深前端王哥】 没问题!百度搜索框的核心效果主要有三个:输入时下拉提示、键盘上下键选择、回车搜索。你想先做哪个?

【前端新手小李】 我想先做输入时实时显示下拉提示,就是输入文字后下面弹出相关建议列表。

【资深前端王哥】 那得监听input事件,然后根据输入值去请求数据或过滤本地数据。你数据从哪来?

【前端新手小李】 我暂时没有后端接口,能不能用本地数组模拟一下?

【资深前端王哥】 可以,比如 const data = ['百度搜索','百度地图','百度网盘','前端开发','JavaScript教程']。输入时用 filter 过滤包含关键词的项。

【前端新手小李】 明白了,过滤后怎么把结果渲染到页面上呢?

【资深前端王哥】 你可以动态创建一个ul,把过滤结果作为li插入,然后绝对定位在输入框下方。记得设置z-index和背景色,否则会挡住其他内容。

【前端新手小李】 我写了一个简单版,但每次输入都会重新创建ul,会不会有性能问题?

【资深前端王哥】 有,最好初始化时就创建好ul,每次只更新innerHTML或使用DOM操作替换子元素。另外可以加个防抖,比如300ms后再执行过滤。

【前端新手小李】 防抖函数我听过,但不太会写。你能给个示例吗?

【资深前端王哥】 function debounce(fn, delay){ let timer; return function(...args){ clearTimeout(timer); timer = setTimeout(()=>fn.apply(this,args), delay); } }

【前端新手小李】 谢谢!那键盘上下键选择怎么实现呢?

【资深前端王哥】 监听keydown事件,判断keyCode是38(上)还是40(下),然后改变一个index变量,给对应的li添加active类,同时把输入框的值设为当前选项的文本。

【前端新手小李】 如果用户按回车呢?

【资深前端王哥】 回车时如果当前有选中项,就执行搜索动作,比如跳转到百度搜索页:window.open('https://www.baidu.com/s?wd=' + encodeURIComponent(value))。如果没有选中项,就用输入框的值。

【前端新手小李】 那点击下拉项也应该能搜索吧?

【资深前端王哥】 对,给每个li绑定click事件,点击后把文本填入输入框并触发搜索。另外点击页面其他地方要隐藏下拉框,可以给document加click事件,判断点击目标是否在搜索框容器内。

【前端新手小李】 我试试看,感觉功能快齐了。还有别的细节吗?

【资深前端王哥】 注意输入框的autocomplete='off',避免浏览器自带的下拉干扰。还有下拉框的显示隐藏用display控制,不要用visibility,否则占位。样式上可以用hover改变背景色,提升体验。

【前端新手小李】 好的,我这就去完善代码。谢谢王哥!

【资深前端王哥】 不客气,有问题随时问。记得测试一下中文输入法组合输入的情况,compositionstart和compositionend事件要处理好。祝顺利!

This article was published byNing Kailiang's Website Building Blog, For more knowledge about“js” please followNing Kailiang's Website Building Blog。

Recent Articles