运行 ❯
获取您的
自己的
网站
×
更改方向
保存代码
更改主题,暗色/亮色
转到 Spaces
<!DOCTYPE html> <html> <head> <style> #container { width: 80%; aspect-ratio: 2/1; margin: auto; border: solid black 2px; overflow-x: hidden; overflow-y: scroll; scroll-snap-type: y mandatory; } .blue { background-color: lightblue; width: 80%; aspect-ratio: 5/2; } .green { background-color: lightgreen; width: 60%; aspect-ratio: 2/1; } .blue, .green { margin: 2px; scroll-snap-align: start; scroll-margin-top: 0; } </style> </head> <body> <h1>Change scroll-margin-top property with JavaScript</h1> <p>Try first to scroll to see how the scroll snaps on start of elements on y-axis.</p> <p>Now, click button, click inside the container, and see how scrolling behaviour has changed. The elements now snap on start of element, but with a 20px margin to container on the top side.</p> <button onclick="myFunction()">Try it</button> <div id="container"> <div class="blue"></div> <div class="green"></div> <div class="blue"></div> <div class="green"></div> <div class="blue"></div> <div class="green"></div> <div class="blue"></div> </div> <script> function myFunction() { let childDiv = document.querySelectorAll("#container>div"); for(let i=0; i<childDiv.length; i++){ childDiv[i].style.scrollMarginTop = "20px"; } } </script> </body> </html>