
实现文本高亮与滚动进度关联的核心思想是:获取当前页面的滚动百分比,然后根据这个百分比来决定文本中应该有多少个单词被“高亮”显示。当用户向下滚动时,高亮词语的数量增加;当用户向上滚动时,高亮词语的数量减少。
首先,我们需要一个基本的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动态填充文本内容的容器。
为了让页面能够滚动,我们需要给 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是实现动态效果的核心。它负责:
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;
}将上述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操作,我们可以实现各种富有创意的滚动驱动动画效果。本文详细介绍了如何根据页面滚动百分比动态高亮文本的实现方法,并提供了完整的代码示例和性能优化建议。掌握这一技术,您可以为您的网页增添独特的交互性和视觉吸引力。在实际项目中,请务必考虑性能优化,以提供流畅的用户体验。
以上就是实现滚动进度驱动的文本高亮效果的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号