如何使用scrollIntoView仅滚动内部容器而不滚动整个body
仅让内部容器滚动到目标元素的解决方案
默认调用scrollIntoView()时,浏览器会触发所有可滚动的祖先容器(包括body)滚动,导致外部容器也跟着移动。要实现仅内部容器滚动的效果,有两种可靠的实现方式:
方式一:通过scrollIntoView配置参数限制滚动范围
给scrollIntoView传入{ block: 'nearest' }参数,该参数会让目标元素仅在最近的可滚动祖先容器内滚动到可见状态,不会触发上层容器(比如body)的滚动:
document.getElementById("target").scrollIntoView({ block: 'nearest' });
如果需要平滑滚动效果,可以追加behavior: 'smooth'配置:
document.getElementById("target").scrollIntoView({ block: 'nearest', behavior: 'smooth' });
方式二:直接操作内部容器的滚动属性
先获取内部容器元素,计算目标元素相对于容器的偏移量,手动设置容器的滚动位置:
const innerContainer = document.querySelector('.innerContainer'); const target = document.getElementById('target'); // 计算目标元素相对于内部容器顶部的偏移值 const targetOffset = target.offsetTop - innerContainer.offsetTop; // 设置内部容器的滚动位置 innerContainer.scrollTop = targetOffset;
同样支持平滑滚动,改用scrollTo方法即可:
const innerContainer = document.querySelector('.innerContainer'); const target = document.getElementById('target'); innerContainer.scrollTo({ top: target.offsetTop - innerContainer.offsetTop, behavior: 'smooth' });
完整可运行代码
CSS
.outerContainer{ height: 150vh; width: 100%; background-color: bisque; } .innerContainer{ width: 500px; height: 80vh; background-color: aqua; overflow: auto; } li{ height: 300px; }
HTML & JavaScript
<div class="outerContainer"> <div class="innerContainer"> <ul> <li>1</li> <li>2</li> <li>3</li> <li id="target">4</li> <li>5</li> </ul> </div> </div> <script> // 任选一种方式即可 document.getElementById("target").scrollIntoView({ block: 'nearest', behavior: 'smooth' }); // 方式二代码(注释掉上面的代码后启用) // const innerContainer = document.querySelector('.innerContainer'); // const target = document.getElementById('target'); // innerContainer.scrollTo({ // top: target.offsetTop - innerContainer.offsetTop, // behavior: 'smooth' // }); </script>
内容的提问来源于stack exchange,提问作者user2401856
相关产品推荐
相关产品推荐

