js实现滚动条
使用原生JavaScript实现滚动条
通过监听滚动事件获取滚动位置
window.addEventListener('scroll', function() {
let scrollPosition = window.scrollY;
console.log('当前滚动位置:', scrollPosition);
});
平滑滚动到指定位置
使用scrollTo方法实现平滑滚动效果

function smoothScrollTo(targetPosition, duration = 1000) {
const startPosition = window.scrollY;
const distance = targetPosition - startPosition;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const run = easeInOutQuad(timeElapsed, startPosition, distance, duration);
window.scrollTo(0, run);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
function easeInOutQuad(t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
}
requestAnimationFrame(animation);
}
自定义滚动条样式
通过CSS隐藏默认滚动条并创建自定义样式
body {
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* IE/Edge */
}
body::-webkit-scrollbar {
display: none; /* Chrome/Safari */
}
.custom-scrollbar {
position: fixed;
right: 0;
top: 0;
width: 10px;
height: 100vh;
background: #f1f1f1;
}
.scroll-thumb {
width: 100%;
background: #888;
border-radius: 5px;
}
同步自定义滚动条
将自定义滚动条与实际滚动位置同步

const scrollThumb = document.querySelector('.scroll-thumb');
const scrollableHeight = document.documentElement.scrollHeight - window.innerHeight;
window.addEventListener('scroll', function() {
const scrollPercentage = (window.scrollY / scrollableHeight) * 100;
const thumbHeight = (window.innerHeight / document.documentElement.scrollHeight) * 100;
scrollThumb.style.height = `${thumbHeight}%`;
scrollThumb.style.transform = `translateY(${scrollPercentage}%)`;
});
滚动到元素位置
实现滚动到页面特定元素的功能
function scrollToElement(elementId) {
const element = document.getElementById(elementId);
if (element) {
const elementPosition = element.getBoundingClientRect().top + window.scrollY;
smoothScrollTo(elementPosition - 20); // 减去20px作为顶部边距
}
}
滚动事件节流优化
使用节流函数优化滚动事件性能
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(function() {
// 滚动处理逻辑
}, 100));






