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

标签 javascript html css

所有页面内容(红色“测试” 在我的图片中)应该放在顶部 100%(应该开始滚动才能看到它)

顶部的Header(在我的图片中用黑色标记)应该固定在页面顶部。
一旦内容到达标题,它就应该开始与其余内容一起滚动。

Visual Representation

(我不知道从哪里开始解决这个问题...没有 JavaScript 可以完成吗?)
预先感谢大家的帮助。

最佳答案

我用几行 JS 代码想出了一个绝招:

jsBin live demo

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

逻辑:

      +--  +----------------+-- (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:

<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:

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%;
}

提示:如果以上内容不清楚,请为我们所有的元素添加不同的背景色。你最好看看会发生什么。

关于javascript - 使固定的顶部元素随页面滚动(一旦内容到达它),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27956266/

相关文章:

javascript - 无法从 API 正确获取数据

php - 防止 php 在 pre 标签之间渲染/执行

javascript - 仅将输入字段中每个单词的第一个字母自动大写

html - 无法将 CSS 应用于 HTML 文档的正文

javascript - 在表格上打印时图像消失

javascript - Chrome 开发者工具 "Properties"部分如何帮助 CSS/JavaScript 开发?

javascript - 如何使用填充的输入值获取当前网站的html源

html - ffmpeg 流桌面代替 -i/dev/video0

javascript - 如何使 JavaScript 代码与 Node.js 一起工作?

html - 如何从 pdf(jspdf) 中去除黑色背景?