javascript - 向下滚动时的 CSS 标题效果(更改背景和颜色)

标签 javascript html css

当 header 离开当前 block 时,我试图做一个很好的效果。我希望向下滚动时背景颜色和文本颜色发生变化。

html:

<header class="green">Logo</header>
<header class="red">Logo</header>

<section id='content1'>
  <h1>Content</h1>
  <p>Goes here!</p>
</section>
<section id='content2'>
  <h1>Content</h1>
  <p>Goes here!</p>
</section>

CSS:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

header {
  width: 100%;
  position: fixed;
  display: block;
  top: 0;
  font-size: 20pt;
  padding: 15px 10px
}

.green {
  background: green;
  color: #000;
  z-index: 2

}
.red {
  background: red;
  color: #fff;
  z-index: 1
}

section {
  position: relative;
  height: 500px;
  padding: 100px 10px
}

#content1 {
  background: #D9D9D9;
  z-index: 1
}

#content2 {
  background: #9FDAD0;
  z-index: 2
}

最好举个例子,像这样https://www.dropbox.com/

谢谢!

最佳答案

所以我用一些 Javascript 重做了它。 这个效果太棒了,如果你喜欢,请随意改进它! 这可以在没有 Javascript 的情况下完成吗?

const secondBlock = document.getElementById('content2')
const header = document.getElementsByTagName('header')
const headerHeight = 61

function setHeader () {
  const scrollPoint = window.pageYOffset + headerHeight

  let blockPoint = 61 - (scrollPoint - secondBlock.offsetTop)
  if (blockPoint <= 0) { blockPoint = 0 }

  if (scrollPoint > secondBlock.offsetTop) {
    header[0].style = `max-height: ${blockPoint}px;`
  } else {
    header[0].style = `max-height: ${headerHeight}px;`
  }
  window.requestAnimationFrame(setHeader)
}

window.requestAnimationFrame(setHeader)
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

header {
  display: block;
  font-size: 20pt;
  height: 61px;
  line-height: 61px;
  padding-left: 10px;
  position: fixed;
  top: 0;
  width: 100%;
}

header#first {
  background: #8292C3;
  color: #000;
  overflow: hidden;
  z-index: 10;
}

header#second {
  background: #82C3B9;
  color: #fff;
  z-index: 9;
}

section {
  height: 500px;
  padding: 100px 10px;
  position: relative;
}

#content1 {
  background: #96A6D5;
}

#content2 {
  background: #99D6CC;
}
<header id='first'>Logo - <small>scroll down to see the magic!</small></header>
<header id='second'>Logo - <small>scroll down to see the magic! COOL!</small></header>

<section id='content1'>
  <h1>Content</h1>
  <p>Goes here!</p>
</section>
<section id='content2'>
  <h1>Content</h1>
  <p>Goes here!</p>
</section>

关于javascript - 向下滚动时的 CSS 标题效果(更改背景和颜色),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53324756/

相关文章:

javascript - 如何在 html 表单中自动插入文本并自动提交?

javascript - 如何使用 jquery 访问 iFrame 父页面?

css - HTML5 视频 : full screen without borders?

html - 我可以隐藏没有类或 ID 的 div 吗? (新台)

javascript - 将复选框方形选项更改为图像

javascript - 如何在 VueJS 0.11 中将 bool 变量输出为 "yes/no"?

javascript - 隐藏基于先前选择的选择选项

javascript - 减少宽度后我应该如何移动div?

javascript - confirm() 如何在 JavaScript 中工作

javascript - 用户输入规则后,如何在 div 中动态应用 css 规则