当我有 .sections
带有多个 .section
的容器里面的元素,并设置滚动捕捉,它只有在我给该部分的固定高度为 100vh 时才会起作用。没有高度,滚动捕捉将不起作用。这很好,除了没有固定高度,scrollTo
工作正常,当我将高度添加到部分时,scrollTo
不再工作。
这是一个例子。您可以注释掉 height: 100vh;
.section
中的行CSS 并看到单击任意位置将向下滚动到第 3 部分,但打开高度后,它不会滚动。
我试过console.log
它滚动到的位置是正确的,但滚动从未真正发生过。关于为什么这不是我想要的方式的任何想法?
注意:我在最新的 Chrome 中看到了这种行为。我还没有测试过其他浏览器。
// Click on document to scroll to section 3
document.body.onclick = function() {
console.log('SCROLLING...');
const el = document.getElementById('s3');
const pos = el.getBoundingClientRect();
window.scrollTo(0, pos.top);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
.sections {
overflow-y: scroll;
scroll-snap-type: y mandatory;
/**
* Adding the below line breaks scrollto, removing
* it breaks scroll-snap....
*/
height: 100vh;
}
.section {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
overflow: hidden;
position: relative;
border: 5px solid deeppink;
font-size: 30px;
font-weight: bold;
scroll-snap-align: center;
}
<html>
<body>
<div class="sections">
<div class="section" id="s1">SECTION 1</div>
<div class="section" id="s2">SECTION 2</div>
<div class="section" id="s3">SECTION 3</div>
<div class="section" id="s4">SECTION 4</div>
<div class="section" id="s5">SECTION 5</div>
</div>
</body>
</html>
最佳答案
感谢@Temani Afif 的评论。他们正确指出我无法使用正文滚动,我需要使用 .sections
滚动容器。
这是一个工作示例:
// Click on document to scroll to section 3
document.body.onclick = function() {
console.log('SCROLLING...');
const el = document.getElementById('s3');
const pos = el.getBoundingClientRect();
const sections = document.querySelector('.sections');
sections.scrollTo(0, pos.top);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
.sections {
overflow-y: scroll;
scroll-snap-type: y mandatory;
height: 100vh;
}
.section {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
overflow: hidden;
position: relative;
border: 5px solid deeppink;
font-size: 30px;
font-weight: bold;
scroll-snap-align: center;
}
<html>
<body>
<div class="sections">
<div class="section" id="s1">SECTION 1</div>
<div class="section" id="s2">SECTION 2</div>
<div class="section" id="s3">SECTION 3</div>
<div class="section" id="s4">SECTION 4</div>
<div class="section" id="s5">SECTION 5</div>
</div>
</body>
</html>
关于javascript - ScrollTo 不适用于滚动快照和 100vh 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59968662/