导航位置在滚动位置时的粘性位置

时间:2020-04-28 09:20:30

标签: javascript css navigation nav sticky

我希望import cv2 import numpy as np import argparse import time t0 = time.time() (code block) cv2.destroyAllWindows() t1 = time.perf_counter() total = print(t1-t0) 用3个数字固定。当到达绿色方块时,它应该超过数字并保持固定并变成红色。当您回到顶部时,它应该回到其原始位置并回到绿色。我将如何实现?

<nav>
.container {
  height: 1000px;
}

nav{
  display: flex;
  justify-content: space-around;
}

.square{
  background-color: green;
  width: 100px;
  height: 100px;
  margin: auto;
  display: block;
  position: sticky;
}

2 个答案:

答案 0 :(得分:0)

要更改背景色,您需要以 animation 的方式查看,但是,根据位置,您需要添加类似top: 0的内容以将组件设置在什么位置保持粘性

答案 1 :(得分:0)

您可以使用javascript检测滚动并使用window.onscroll向元素添加粘性类,还请注意,在使用sticky CSS属性值进行显示时,您还应该调整位置,我使用calc来计算左值,这是一个有效的代码段:

window.onscroll = function() {myFunction()};

var header = document.querySelector(".square");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}
.container {
  height: 10000px;
}

nav {
  display: flex;
  justify-content: space-around;
}

.square {
  background-color: green;
  width: 100px;
  height: 100px;
  margin: auto;
  display: block;
}

.sticky {
  position: fixed;
  top: 0;
  background-color:red;
  left: calc((100% - 100px)/2);
}

.sticky + .content {
  padding-top: 102px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div class="container">
  <header>
    <nav>
      <p>1</p>
      <p>2</p>
      <p>3</p>
    </nav>
  </header>


  <div class="square"></div>

</div>
</body>
</html>