本教程将详细介绍如何利用JavaScript监听浏览器滚动事件,实现文本内容根据页面滚动百分比进行动态填充或高亮的效果。通过计算滚动位置,我们可以实时更新文本的样式,使其从左到右逐渐着色,并在回滚时取消着色,从而创造出独特的视觉交互体验。文章将提供完整的HTML、CSS和JavaScript代码示例,并探讨实现细节及注意事项。
核心原理
实现文本高亮与滚动进度关联的核心思想是:获取当前页面的滚动百分比,然后根据这个百分比来决定文本中应该有多少个单词被“高亮”显示。当用户向下滚动时,高亮词语的数量增加;当用户向上滚动时,高亮词语的数量减少。
HTML 结构
首先,我们需要一个基本的HTML页面结构,其中包含一个用于显示动态文本的容器。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>滚动进度文本高亮</title> <link rel="stylesheet" href="style.css"> </head> <body> <span class="text"></span> <script src="script.js"></script> </body> </html>
这里,<span class=”text”></span> 是我们将通过JavaScript动态填充文本内容的容器。
CSS 样式
为了让页面能够滚动,我们需要给 body 设置足够的高度。同时,为了让文本在滚动时保持在视口内,我们可以使用 position: fixed。最后,定义高亮文本的样式。
body { height: 5000px; /* 确保页面有足够的滚动空间 */ margin: 0; font-family: Arial, sans-serif; line-height: 1.6; } .text { position: fixed; /* 使文本在滚动时保持在视口顶部 */ top: 10px; left: 10px; max-width: 80%; /* 防止文本过宽 */ background-color: #f9f9f9; padding: 10px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); } .text span { transition: color 0.1s ease-out; /* 为颜色变化添加平滑过渡 */ } .highlight { color: #f00; /* 高亮文本的颜色,这里设置为红色 */ font-weight: bold; }
JavaScript 逻辑
JavaScript是实现动态效果的核心。它负责:
- 获取原始文本并将其拆分成单词。
- 将每个单词包裹在 <span> 标签中,以便单独控制样式。
- 监听 scroll 事件,计算当前滚动百分比。
- 根据滚动百分比,动态更新文本中高亮单词的数量。
const HIGHLIGHT_CLASS = 'highlight'; // 定义高亮CSS类名 const LOREM_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer suscipit libero eu ligula molestie, sed faucibus leo iaculis. Quisque scelerisque ligula in volutpat venenatis. Fusce velit felis, pretium eu varius quis, facilisis eget nunc. Quisque eu eros tellus. Cras condimentum efficitur turpis, ac laoreet velit rhoncus et. Maecenas non lorem auctor dolor auctor gravida ut at diam. Proin eleifend elementum lacus in varius. In dapibus mi ut erat gravida, non dictum nisi luctus. Aliquam imperdiet commodo ante, posuere vestibulum eros mattis vitae. Cras molestie commodo turpis, vitae tempus magna dictum pharetra. Duis quis eros at magna sodales mollis. Fusce sollicitudin purus sit amet est ullamcorper luctus. Donec molestie, nisi quis luctus malesuada, lectus arcu rutrum turpis, ac bibendum libero tellus at metus. Vivamus mattis ultricies metus eu dignissim. Mauris sed consectetur nisl."; let words = LOREM_TEXT.split(" "); // 将文本按空格拆分为单词数组 let textContainer = document.querySelector('.text'); // 获取文本容器元素 // 初始化文本内容,将每个单词包裹在<span>中 textContainer.innerHTML = words .map(w => `<span>${w}</span>`) .join(' '); // 监听窗口滚动事件 window.addEventListener('scroll', () => { let scrollFraction = getScrollFraction(); // 获取当前滚动百分比 (0-1之间) let wordsToHighlightCount = Math.floor(scrollFraction * words.length); // 根据滚动百分比计算需要高亮的单词数量 // 重新渲染文本内容,为需要高亮的单词添加CSS类 textContainer.innerHTML = words .map((word, index) => `<span ${index < wordsToHighlightCount ? `class="${HIGHLIGHT_CLASS}"` : ''}>${word}</span>`) .join(' '); }); /** * 计算页面滚动百分比的辅助函数。 * 返回一个0到1之间的浮点数,表示当前滚动位置占总可滚动高度的比例。 */ function getScrollFraction() { var docElem = document.documentElement, bodyElem = document.body, scrollTopProp = 'scrollTop', scrollHeightProp = 'scrollHeight'; // 获取当前滚动条位置 (兼容不同浏览器) var currentScrollTop = docElem[scrollTopProp] || bodyElem[scrollTopProp]; // 获取可滚动总高度 var totalScrollHeight = (docElem[scrollHeightProp] || bodyElem[scrollHeightProp]) - docElem.clientHeight; // 避免除以零的情况 if (totalScrollHeight <= 0) { return 0; } return currentScrollTop / totalScrollHeight; }
代码解析:
- HIGHLIGHT_CLASS 和 LOREM_TEXT: 定义了高亮CSS类名和作为示例的文本内容。
- words = LOREM_TEXT.split(” “);: 将长文本分割成单词数组。
- 初始化 textContainer.innerHTML: 在页面加载时,将每个单词用 <span> 标签包裹起来,并插入到 .text 容器中。这样做的目的是为了能够独立地为每个单词添加或移除高亮样式。
- window.addEventListener(‘scroll’, …): 注册一个滚动事件监听器,每当页面滚动时,其中的回调函数就会被执行。
- getScrollFraction(): 这是一个关键的辅助函数,它计算当前页面的滚动百分比。
- document.documentElement.scrollTop 或 document.body.scrollTop 获取当前滚动条距离页面顶部的距离。
- (document.documentElement.scrollHeight || document.body.scrollHeight) – document.documentElement.clientHeight 计算总的可滚动高度(即文档总高度减去视口高度)。
- 两者相除即可得到滚动百分比(0到1之间)。
- *`wordsToHighlightCount = Math.floor(scrollFraction words.length);**: 根据滚动百分比,计算出当前应该高亮的单词数量。Math.floor` 确保得到一个整数。
- 重新渲染 textContainer.innerHTML: 这是实现动态高亮的核心。它遍历 words 数组,如果当前单词的索引小于 wordsToHighlightCount,则为其 <span> 标签添加 HIGHLIGHT_CLASS。然后将所有 <span> 重新拼接成字符串,并更新 textContainer 的 innerHTML。
完整代码示例
将上述HTML、CSS和JavaScript代码分别保存为 index.html、style.css 和 script.js,并确保它们在同一目录下。
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>滚动进度文本高亮</title> <link rel="stylesheet" href="style.css"> </head> <body> <span class="text"></span> <script src="script.js"></script> </body> </html>
style.css
body { height: 5000px; /* 确保页面有足够的滚动空间 */ margin: 0; font-family: Arial, sans-serif; line-height: 1.6; } .text { position: fixed; /* 使文本在滚动时保持在视口顶部 */ top: 10px; left: 10px; max-width: 80%; /* 防止文本过宽 */ background-color: #f9f9f9; padding: 10px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); } .text span { transition: color 0.1s ease-out; /* 为颜色变化添加平滑过渡 */ } .highlight { color: #f00; /* 高亮文本的颜色,这里设置为红色 */ font-weight: bold; }
script.js
const HIGHLIGHT_CLASS = 'highlight'; // 定义高亮CSS类名 const LOREM_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer suscipit libero eu ligula molestie, sed faucibus leo iaculis. Quisque scelerisque ligula in volutpat venenatis. Fusce velit felis, pretium eu varius quis, facilisis eget nunc. Quisque eu eros tellus. Cras condimentum efficitur turpis, ac laoreet velit rhoncus et. Maecenas non lorem auctor dolor auctor gravida ut at diam. Proin eleifend elementum lacus in varius. In dapibus mi ut erat gravida, non dictum nisi luctus. Aliquam imperdiet commodo ante, posuere vestibulum eros mattis vitae. Cras molestie commodo turpis, vitae tempus magna dictum pharetra. Duis quis eros at magna sodales mollis. Fusce sollicitudin purus sit amet est ullamcorper luctus. Donec molestie, nisi quis luctus malesuada, lectus arcu rutrum turpis, ac bibendum libero tellus at metus. Vivamus mattis ultricies metus eu dignissim. Mauris sed consectetur nisl."; let words = LOREM_TEXT.split(" "); // 将文本按空格拆分为单词数组 let textContainer = document.querySelector('.text'); // 获取文本容器元素 // 初始化文本内容,将每个单词包裹在<span>中 textContainer.innerHTML = words .map(w => `<span>${w}</span>`) .join(' '); // 监听窗口滚动事件 window.addEventListener('scroll', () => { let scrollFraction = getScrollFraction(); // 获取当前滚动百分比 (0-1之间) let wordsToHighlightCount = Math.floor(scrollFraction * words.length); // 根据滚动百分比计算需要高亮的单词数量 // 重新渲染文本内容,为需要高亮的单词添加CSS类 textContainer.innerHTML = words .map((word, index) => `<span ${index < wordsToHighlightCount ? `class="${HIGHLIGHT_CLASS}"` : ''}>${word}</span>`) .join(' '); }); /** * 计算页面滚动百分比的辅助函数。 * 返回一个0到1之间的浮点数,表示当前滚动位置占总可滚动高度的比例。 */ function getScrollFraction() { var docElem = document.documentElement, bodyElem = document.body, scrollTopProp = 'scrollTop', scrollHeightProp = 'scrollHeight'; // 获取当前滚动条位置 (兼容不同浏览器) var currentScrollTop = docElem[scrollTopProp] || bodyElem[scrollTopProp]; // 获取可滚动总高度 var totalScrollHeight = (docElem[scrollHeightProp] || bodyElem[scrollHeightProp]) - docElem.clientHeight; // 避免除以零的情况 if (totalScrollHeight <= 0) { return 0; } return currentScrollTop / totalScrollHeight; }
注意事项与优化
-
性能考量: 频繁地修改 innerHTML 会导致浏览器重新解析和渲染DOM,这在滚动事件中可能会引起性能问题,尤其是在长文本或复杂页面上。
-
优化方案: 可以考虑只更新每个 <span> 元素的 class 属性,而不是整个 innerHTML。这需要先获取所有的 <span> 元素,然后根据滚动进度遍历并修改它们的 classList。例如:
// 优化后的滚动事件处理 let spans = textContainer.querySelectorAll('span'); // 获取所有span元素一次 window.addEventListener('scroll', () => { let scrollFraction = getScrollFraction(); let wordsToHighlightCount = Math.floor(scrollFraction * words.length); spans.forEach((span, index) => { if (index < wordsToHighlightCount) { span.classList.add(HIGHLIGHT_CLASS); } else { span.classList.remove(HIGHLIGHT_CLASS); } }); });
这种方式避免了DOM的完全重建,性能会更好。
-
-
滚动速度与文本长度: 示例中 body 高度为5000px,文本较短。如果文本很长,或者页面可滚动高度很小,高亮效果可能会显得过快或过慢。可以调整 body 的高度或文本长度来平衡效果。
-
平滑过渡: 通过CSS transition 属性 (.text span { transition: color 0.1s ease-out; }) 可以让颜色变化更加平滑,提升用户体验。
-
样式定制: 高亮效果不限于改变颜色,还可以是背景色、字体粗细、渐变填充等。只需修改 .highlight CSS 类即可实现。
-
节流/防抖: 滚动事件触发非常频繁。在某些复杂场景下,可以考虑使用节流(throttle)或防抖(debounce)函数来限制事件处理函数的执行频率,进一步优化性能。
总结
通过结合JavaScript的滚动事件监听和DOM操作,我们可以实现各种富有创意的滚动驱动动画效果。本文详细介绍了如何根据页面滚动百分比动态高亮文本的实现方法,并提供了完整的代码示例和性能优化建议。掌握这一技术,您可以为您的网页增添独特的交互性和视觉吸引力。在实际项目中,请务必考虑性能优化,以提供流畅的用户体验。
css javascript word java html js 浏览器 回调函数 ssl ai win JavaScript css html math 回调函数 字符串 class Length JS 事件 dom innerHTML position transition 性能优化