运行 ❯
获取您
自身
网站
×
更改方向
保存代码
更改主题,深色/浅色
前往空间
<!DOCTYPE html> <html> <head> <style> #container { width: 80%; aspect-ratio: 3/2; margin: auto; border: solid black 2px; overflow-x: scroll; overflow-y: hidden; white-space: nowrap; scroll-snap-type: x mandatory; } .blue { background-color: lightblue; height: 95%; aspect-ratio: 1/2; } .green { background-color: lightgreen; height: 50%; aspect-ratio: 2/1; } .blue, .green { display: inline-block; margin: 5px; scroll-snap-align: none center; } </style> </head> <body> <h1>Change scroll-snap-align property with JavaScript</h1> <p>Try first to scroll to see how the scroll-snap-align works when centered on x-axis.</p> <p>Now, click button, and see how scrolling behavior has changed. The elements now snap on start of element.</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.scrollSnapAlign = "start"; } } </script> </body> </html>