几行CSS和JS代码实现粘性元素固定并监听何时固定
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sticky</title> <style> html, body { margin: 0; padding: 0; } .block { height: 100px; } #parent { height: 2000px; } .myElement { position: sticky; top: -1px; height: 60px; display: flex; align-items: center; justify-content: center; background-color: skyblue; color: snow; } /* styles for when the header is in sticky mode */ .myElement.is-pinned { color: red; } </style> </head> <body> <div id="parent"> <div class="block"></div> <div class="myElement">Tittle</div> </div> </body> <script> const el = document.querySelector(".myElement") const observer = new IntersectionObserver( ([e]) => e.target.classList.toggle("is-pinned", e.intersectionRatio < 1), { threshold: [1] } ); observer.observe(el); </script> </html>