Jer*_*ris 7 html javascript css js-scrollto scroll-snap
当我有一个内部.sections包含多个.section元素的容器并设置滚动捕捉时,只有当我为该部分指定 100vh 的固定高度时,它才会起作用。如果没有高度,滚动捕捉将不起作用。这很好,除了没有固定高度,scrollTo工作正常,当我将高度添加到该部分时,scrollTo不再工作。
这是一个例子。height: 100vh;您可以在CSS 中注释掉该行.section,然后看到单击任意位置都会向下滚动到第 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);
}Run Code Online (Sandbox Code Playgroud)
* {
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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
感谢@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);
}Run Code Online (Sandbox Code Playgroud)
* {
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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3776 次 |
| 最近记录: |