You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JS实现搜索后平滑滚动、高亮父级div及多结果切换

游泳者搜索功能优化方案

问题分析

原代码依赖过时的window.find()和IE专属TextRange API,导致Safari兼容问题;仅通过文本选中实现高亮,视觉效果弱;无平滑滚动逻辑;不支持多匹配结果遍历。以下是完整的修复与优化实现:


1. HTML调整(移除内联事件,保持结构简洁)

<div id="stickysearch">
    <div>
        <h4><strong>Search for a swimmer</strong></h4>
        <form id="f1" name="f1" action="">
            <input type="text" id="t1" name="t1" value="" size="20" placeholder="Enter a name">
            <input type="submit" name="b1" value="Find">
        </form>
    </div>
</div>

2. 高亮样式(醒目且兼容所有设备)

/* 添加到页面样式表或<style>标签中 */
.swimmer-highlight {
  outline: 3px solid #ff6b6b; /* 高对比度红色边框 */
  background-color: rgba(255, 107, 107, 0.1); /* 淡红色背景增强视觉 */
  transition: all 0.3s ease; /* 平滑过渡效果 */
}

3. JavaScript实现(现代API,兼容Safari,支持平滑滚动与多结果遍历)

// 全局存储匹配结果与当前索引
let matches = [];
let currentMatchIndex = -1;

// 获取DOM元素
const searchForm = document.getElementById('f1');
const searchInput = document.getElementById('t1');
const submitBtn = document.querySelector('input[name="b1"]');
// 匹配测试页面中游泳者卡片的选择器(根据实际结构调整)
const swimmerCards = document.querySelectorAll('.col-lg-4.col-md-6.mb-4');

// 核心搜索函数:筛选匹配的游泳者卡片
function searchSwimmers(query) {
  // 重置之前的高亮与状态
  matches.forEach(card => card.classList.remove('swimmer-highlight'));
  matches = [];
  currentMatchIndex = -1;

  if (!query.trim()) {
    submitBtn.value = 'Find';
    alert('Please enter a name to search.');
    return;
  }

  // 遍历所有卡片,匹配姓名(不区分大小写)
  swimmerCards.forEach(card => {
    const swimmerName = card.querySelector('h3').textContent.toLowerCase();
    if (swimmerName.includes(query.toLowerCase())) {
      matches.push(card);
    }
  });

  if (matches.length === 0) {
    submitBtn.value = 'Find';
    alert(`Sorry, Swimmer '${query}' can’t be found.`);
    return;
  }

  // 根据匹配数量切换按钮文本
  submitBtn.value = matches.length > 1 ? 'Next' : 'Find';
  // 跳转到第一个匹配项
  goToMatch(0);
}

// 滚动并高亮指定匹配项
function goToMatch(index) {
  // 移除上一个匹配项的高亮
  if (currentMatchIndex !== -1) {
    matches[currentMatchIndex].classList.remove('swimmer-highlight');
  }
  currentMatchIndex = index;
  const targetCard = matches[currentMatchIndex];
  
  // 添加高亮样式
  targetCard.classList.add('swimmer-highlight');
  // 平滑滚动到目标卡片并居中显示
  targetCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

// 表单提交事件处理
searchForm.addEventListener('submit', function(e) {
  e.preventDefault();
  const query = searchInput.value.trim();
  
  if (currentMatchIndex === -1 || matches.length === 0) {
    // 首次搜索:执行匹配筛选
    searchSwimmers(query);
  } else {
    // 已有匹配:切换到下一个(循环遍历)
    let nextIndex = currentMatchIndex + 1;
    if (nextIndex >= matches.length) {
      nextIndex = 0;
    }
    goToMatch(nextIndex);
  }
});

关键功能说明

  • Safari兼容:完全使用现代DOM API(querySelectorAll、textContent、scrollIntoView),替代过时的浏览器专属方法,解决Safari失效问题。
  • 醒目高亮:通过自定义CSS类为父容器添加高对比度边框与背景,比文本选中效果更清晰,适配所有设备。
  • 平滑滚动:利用scrollIntoView的smooth行为参数,实现自然的滚动过渡,同时设置block: 'center'让目标卡片在视口中居中。
  • 多结果遍历:自动存储所有匹配卡片,点击按钮时循环切换到下一个匹配项,按钮文本根据匹配数量自动调整。

内容的提问来源于stack exchange,提问作者SharkRhys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 14:17:14