js 实现div滚动
实现 div 滚动的方法
使用 scrollTo 方法
通过 JavaScript 的 scrollTo 方法可以控制 div 的滚动位置。该方法接受两个参数,分别是水平滚动位置和垂直滚动位置。
const div = document.getElementById('scrollableDiv');
div.scrollTo(0, 100); // 滚动到垂直位置 100px
如果需要平滑滚动,可以传入一个配置对象:
div.scrollTo({
top: 100,
left: 0,
behavior: 'smooth'
});
使用 scrollTop 和 scrollLeft 属性
直接修改 scrollTop 或 scrollLeft 属性可以实现滚动效果。
const div = document.getElementById('scrollableDiv');
div.scrollTop = 100; // 垂直滚动到 100px
div.scrollLeft = 50; // 水平滚动到 50px
监听滚动事件
可以通过监听 scroll 事件来触发自定义逻辑。

const div = document.getElementById('scrollableDiv');
div.addEventListener('scroll', function() {
console.log('当前滚动位置:', div.scrollTop);
});
滚动到指定元素
如果需要滚动到 div 内的某个子元素,可以使用 scrollIntoView 方法。
const childElement = document.getElementById('targetElement');
childElement.scrollIntoView({
behavior: 'smooth',
block: 'nearest'
});
自动滚动动画
通过 requestAnimationFrame 实现平滑滚动动画。

function smoothScroll(element, targetPosition, duration) {
const startPosition = element.scrollTop;
const distance = targetPosition - startPosition;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const progress = Math.min(timeElapsed / duration, 1);
element.scrollTop = startPosition + distance * progress;
if (timeElapsed < duration) {
requestAnimationFrame(animation);
}
}
requestAnimationFrame(animation);
}
const div = document.getElementById('scrollableDiv');
smoothScroll(div, 200, 500); // 滚动到 200px,动画时长 500ms
使用 CSS 控制滚动行为
通过 CSS 的 overflow 属性可以启用 div 的滚动功能。
.scrollable-div {
overflow: auto; /* 自动显示滚动条 */
height: 200px;
}
结合 JavaScript 动态调整滚动行为:
const div = document.getElementById('scrollableDiv');
div.style.overflow = 'scroll'; // 强制显示滚动条
滚动到顶部或底部
通过设置 scrollTop 为 0 或 scrollHeight 可以滚动到顶部或底部。
const div = document.getElementById('scrollableDiv');
div.scrollTop = 0; // 滚动到顶部
div.scrollTop = div.scrollHeight; // 滚动到底部






