基于jQuery实现搜索输入时滚动到对应产品的问题求助
问题:搜索输入时无法滚动到对应产品元素
我用HTML、CSS、JS搭建了一个网站,现在遇到个小问题:已经完成搜索表单的HTML和CSS编写,想实现用户在搜索框输入产品名称时,页面自动滚动到对应的产品位置。具体需求是:当用户在类名为.text_2_Rapid_Item_1的输入框输入内容时,页面滚动到包含该产品名称、类名为.Rapid_Item_1的产品元素处,但我写的jQuery代码没生效,求解决办法。
我的代码:
// scroll to current product (it didn't work) $(function () { $(".text_2_Rapid_Item_1").on("input", function () { $(".Rapid_Item_1").get(0).scrollIntoView({ block: "start", behavior: "smooth", }); }); });
解决方案
你的代码存在两个核心问题:
- 未关联输入内容与目标元素:当前代码不管输入什么,都会直接滚动到第一个
.Rapid_Item_1元素,完全没用到输入的产品名称做匹配。 - 无异常处理逻辑:如果页面中没有
.Rapid_Item_1元素,调用get(0)会直接报错,导致整个代码失效。
修改后的代码
$(function () { $(".text_2_Rapid_Item_1").on("input", function () { // 获取输入内容,去除首尾空格并统一为小写(实现忽略大小写的模糊匹配) const inputContent = $(this).val().trim().toLowerCase(); if (!inputContent) return; // 输入为空时不执行操作 // 筛选出包含输入内容的产品元素 const targetProduct = $(".Rapid_Item_1").filter(function() { const productName = $(this).text().trim().toLowerCase(); return productName.includes(inputContent); }).first(); // 取第一个匹配的产品 // 找到目标元素后执行滚动 if (targetProduct.length > 0) { targetProduct.get(0).scrollIntoView({ block: "start", behavior: "smooth" }); } }); });
额外优化建议
- 添加防抖处理:避免用户快速输入时频繁触发滚动,提升性能:
$(function () { let debounceTimer; $(".text_2_Rapid_Item_1").on("input", function () { clearTimeout(debounceTimer); debounceTimer = setTimeout(() => { const inputContent = $(this).val().trim().toLowerCase(); if (!inputContent) return; const targetProduct = $(".Rapid_Item_1").filter(function() { const productName = $(this).text().trim().toLowerCase(); return productName.includes(inputContent); }).first(); if (targetProduct.length > 0) { targetProduct.get(0).scrollIntoView({ block: "start", behavior: "smooth" }); } }, 300); // 300毫秒延迟,可根据需求调整 }); }); - 切换精确匹配:如果需要严格匹配产品名称,将
includes替换为===即可。
内容的提问来源于stack exchange,提问作者I'm good
相关产品推荐
相关产品推荐

