Hide scrollable content behind transparent fixed position divs when scrolling the page?

后端 未结 10 1080
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 09:16

I have a div called header that is set up with a fixed position. The problem is when I scroll the page the content of the page shows up behind the header (the header is tran

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 10:14

    Just came up with a new solution to this type of problem that I'm quite happy with.

    Use clip-path on the content that needs to hide behind the transparent element. Then update the clip-path dynamically with js on window scroll.

    HTML

    Sticky content

    JS

    window.addEventListener("scroll",function(){
      const windowScrollTop = window.scrollTop;
      const elementToHide = document.getElementById("content");
    
      elementToHide.style.clipPath = `inset(${windowScrollTop}px 0 0 0)`;
    });
    

    Dynamic sticky content

    In my case I had an element that I switched to position: sticky after scrolling past it. The #sticky content needs to be relative to the dom elements that came before it until we have scrolled far enough. Here's how I accounted for that:

    HTML

    Here's some other stuff
    Sticky content

    JS

    window.addEventListener("scroll",function(){
      const windowScrollTop = window.scrollTop;
      const stickyElement = document.getElementById("sticky");
      const elementToHide = document.getElementById("content");
      const stickyElementTop = stickyElement.getBoundingClientRect().top
    
      if(windowScrollTop >= stickyElementTop){
        stickyElement.style.position = "sticky";
        elementToHide.style.clipPath = `inset(${windowScrollTop - stickyElementTop}px 0 0 0)`;
      }
      else {
        stickyElement.style.position = "relative";
        elementToHide.style.clipPath = "none";
      }
    });
    

提交回复
热议问题