# JS scroll Event ## 相關函式 | 事件名 | 觸發時機 | |:----- |:------ | | scrollX | 沿X軸滾動時 | | scrollY | 沿Y軸滾動時 | --- ## 範例 :::spoiler **scroll event** CSS ```CSS! <style> #block{ border: 1px solid green; height: 200px; margin-top: 50px; margin-bottom: 1000px; } .bg_gray{ background-color: gray; } </style> ``` HTML ```HTML! <div id="block">這是內容(螢幕上方碰到,背景變灰色)</div> ``` JS ```javascript! <script> let my_block = document.getElementById("block"); window.addEventListener("scroll", function(){ console.log( my_block.getBoundingClientRect().top ); if(my_block.getBoundingClientRect().top <= 0){ my_block.classList.add("bg_gray"); } else if (my_block.getBoundingClientRect().top > 0) { my_block.classList.remove("bg_gray"); } }); </script> ``` ::: * 說明:應用 `getBoundingClientRect()` 函式 和 `if`判斷式 * Demo: ![](https://i.imgur.com/zTJCOHQ.gif) ###### tags: `frontend` `jsnote` [:arrow_right: Back to Front End Homepage :arrow_left:](/S-c0eqQmS16D8tcTx4ae1g)