当前位置:网站首页>Issue 003 how to detect whether a sticky positioned element is in a pinned state

Issue 003 how to detect whether a sticky positioned element is in a pinned state

2022-06-24 17:07:00 Front end gogogogo

Scene description

sticky Elements of positioning , There are two states : Relative positioning and fixed positioning . When developing , There is a fixed position (Pined) state sticky Positioned elements plus additional styling requirements . Such as adding a shadow effect .

sticky-width-shadow.gif

at present , It's impossible to pass CSS know sticky Whether it is in the state of fixed positioning .

Solution

For this scenario , It can be used JS Realization .

Determine whether the element is in a fixed positioning state , It is to judge the position relationship between this element and the scrolling parent element .

When the element part is in the fixed positioning state , It is not visible relative to the parent element portion of the scroll . It can be used Intersection Observer To listen for the positional relationship between this element and the scrolling parent element .

The following is the specific code implementation :

intersectionRatio: The visible proportion of the target element , namely intersectionRect Occupy boundingClientRect The proportion of , When fully visible 1, Less than or equal to when completely invisible 0.

threshold1: List of listening thresholds , In ascending order , Each threshold in the list is the ratio of the cross region to the boundary region of the listener . When fully visible 1, Less than or equal to when completely invisible 0.

//  Target element 
const el = document.querySelector(".myElement")
const observer = new IntersectionObserver(
  ([e]) =>
    e
      .target
      .classList
      .toggle(
        "is-pinned",
        e.intersectionRatio < 1
      ),
  {
    threshold: [1] 
  }
)
//  monitor 
observer.observe(el)
/* sticky  Elements  */
.myElement {
  position: sticky;
  top: -1px;
}
/*  Style of fixed positioning state  */
.is-pinned {
  color: red;
}

If you are in a fixed position sticky Element shading , Yes CSS Solutions for : Shadowy CSS Sticky.

Reference resources

原网站

版权声明
本文为[Front end gogogogo]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/03/20210331151845263j.html

随机推荐