在现代Web开发中,我们经常需要根据页面滚动位置来动态改变元素的样式。这可以通过原生JavaScript的滚动事件监听和DOM操作来实现,而不需要依赖jQuery。
使用window.addEventListener('scroll', callback)
来监听页面滚动事件。
通过window.scrollY
或window.pageYOffset
获取垂直滚动位置。
使用element.style.property
或element.classList
方法来修改元素的样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>滚动改变样式</title>
<style>
body {
height: 2000px; /* 使页面可滚动 */
margin: 0;
font-family: Arial, sans-serif;
}
#targetDiv {
position: fixed;
top: 20px;
left: 20px;
width: 200px;
height: 200px;
background-color: #3498db;
color: white;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
}
.scrolled-style {
background-color: #e74c3c;
border-radius: 50%;
transform: rotate(45deg);
}
</style>
</head>
<body>
<div id="targetDiv">滚动改变我的样式</div>
<script>
// 获取目标元素
const targetDiv = document.getElementById('targetDiv');
// 定义触发样式改变的滚动位置阈值
const scrollThreshold = 300;
// 滚动事件处理函数
function handleScroll() {
// 获取当前滚动位置
const scrollPosition = window.scrollY || window.pageYOffset;
// 检查是否超过阈值
if (scrollPosition > scrollThreshold) {
// 添加新样式类
targetDiv.classList.add('scrolled-style');
} else {
// 移除样式类
targetDiv.classList.remove('scrolled-style');
}
// 或者直接修改样式属性
// targetDiv.style.backgroundColor = scrollPosition > scrollThreshold ? '#e74c3c' : '#3498db';
// targetDiv.style.borderRadius = scrollPosition > scrollThreshold ? '50%' : '0';
}
// 添加滚动事件监听
window.addEventListener('scroll', handleScroll);
// 初始调用一次以设置初始状态
handleScroll();
</script>
</body>
</html>
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
}
}
// 使用节流
window.addEventListener('scroll', throttle(handleScroll, 100));
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// 元素进入视口
entry.target.classList.add('scrolled-style');
} else {
// 元素离开视口
entry.target.classList.remove('scrolled-style');
}
});
}, {threshold: 0.1}); // 当10%的元素可见时触发
observer.observe(targetDiv);
问题1:滚动事件性能问题
问题2:样式改变不流畅
问题3:移动端兼容性问题
window.pageYOffset
而不是document.body.scrollTop
等可能不兼容的属性通过以上方法,你可以轻松实现不依赖jQuery的滚动位置样式改变效果。
没有搜到相关的沙龙