Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

การตรวจจับเมื่ออิลิเมนต์กลายเป็น Fixed ด้วย CSS position:sticky และ Intersection Observer

ด้วยการใช้สไตล์ CSS ต่างๆ กับองค์ประกอบที่มี position: sticky เราสามารถตรวจจับได้อย่างง่ายดายเมื่อมันกลายเป็น fixed

ตัวอย่าง

<!DOCTYPE html> 
<html> 
<head> 
<style> 
#first { 
  background-color: lightgrey; 
  height: 10px; 
} 
#navbar-top { 
  background-color: lightgrey; 
  height: 2px; 
} 
#container { 
  position: sticky; 
  top: 0; 
  box-shadow: inset 0 0 25px navy; 
  height: 55px; 
  text-align: center; 
  font-size: 24px; 
  line-height: 55px; 
  font-weight: bold; 
  transition: font-size 0.4s ease-in; 
} 
.sticky-navbar { 
  box-shadow: inset 0 0 15px orange !important; 
  font-size: 20px !important; 
} 
#parent-container { 
  background-color: aliceblue; 
  height: 3300px; 
} 
</style> 
</head> 
<body> 
<div id="first"></div> 
<div id="navbar-top"></div> 
<div id="container">Watch Me!</div> 
<div id="parent-container"></div> 
<script> 
let newObserver = new IntersectionObserver(function(entries) { 
  if(entries[0].intersectionRatio === 0) 
    document.querySelector("#container").classList.add("sticky-navbar"); 
  else if(entries[0].intersectionRatio === 1) 
    document.querySelector("#container").classList.remove("sticky-navbar"); 
}, { threshold: [0,1] }); 
newObserver.observe(document.querySelector("#navbar-top")); 
</script> 
</body> 
</html>

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้:

การตรวจจับเมื่ออิลิเมนต์กลายเป็น Fixed ด้วย CSS position:sticky และ Intersection Observer

การตรวจจับเมื่ออิลิเมนต์กลายเป็น Fixed ด้วย CSS position:sticky และ Intersection Observer