简体   繁体   English

使固定的顶部元素随页面滚动(一旦内容到达页面)

[英]Make fixed top element scroll with page (once the content reaches it)

All the page content ( red "Test" in my image) should be placed at top 100% (one should start scroll to see it) 所有页面内容(图像中的红色“测试”都应置于顶部100%)(应该开始滚动以查看它)

The top Header (Marked with black in my image) should be fixed to the page top. 顶部标头(在我的图像中标记为黑色)应固定在页面顶部。
once the Content hits the header it should start scroll with the rest of the content. 一旦内容到达标题,它应该开始与其余内容滚动。

视觉表现

(I have no clue where to start with this problem... Can it be done without JavaScript ?) (我不知道从哪里开始这个问题。 没有JavaScript可以完成吗?)
Thanks in advance for your help everyone. 在此先感谢大家的帮助。

I've come up with a nice trick with a couple of JS lines : 我提出了一个不错的技巧,包含了几行JS代码

jsBin live demo jsBin现场演示

var heaF = document.getElementById("headerFixed");
var heaC = document.getElementById("headerClone");

heaC.innerHTML = heaF.innerHTML;            // Clone header content (SEO wise)

function hero(){
  var t = heaC.getBoundingClientRect().top; // Keep track of the clone top pos.
  heaF.style.opacity = t<0 ? 0 : 1;         // Toggle Org header opacity
  heaC.style.opacity = t<0 ? 1 : 0;         // Toggle Clone header opacity
}

hero();                 // Do it when DOM is read
window.onscroll = hero; // Do it on scroll
window.onresize = hero; // But also on rresize

The logic: 逻辑:

      +--  +----------------+-- (Viewport Top)
      |    |   headerFixed  |   opacity:1; 0 when the Clone hits Viewp.Top
      h    +----------------+
      e    |                |
      r    |                |
      o    +----------------+
      |    #   headerClone  |   opacity:0; 1 when it hits Viewp.Top
      +--  +----------------+-- (Viewport Bottom)
           |   Content...   |   
           ⋮                 ⋮         

HTML: HTML:

<div id="hero">
    <div id="headerFixed"><h1>Header</h1></div>
    <div id="headerClone"></div>
</div>
<div id="content">Website template and content here</div>

CSS: CSS:

html, body { height:100%; }
#hero{              // This guy contains header and the JS cloned header
    height:100%;       // In order to cover the whole viewport height
}
#headerFixed {
    position: fixed;   // Will be always fixed!
    width: 100%;
}
#headerClone{         
    position:absolute; 
    bottom:0;          // Place it at the bottom
    opacity:0;         // (Uncomment this line to see it in action)
    width:100%;
}

Tip: if the above is not clear, add different background-color to all our elements. 提示:如果以上内容不清楚,请为所有元素添加不同的背景色。 You should better see what happens. 您应该最好看看会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM