如何显示单独的锂元素滚动基于窗口的高度

How to show individual li-elements on scroll based on window height

本文关键字:于窗口 窗口 高度 滚动 元素 何显示 显示 单独      更新时间:2023-09-26

我正试图根据页面滚动的距离为我的每个LI元素添加一个类。

如果我的视口是2000px高,第一个li应该在500px之后添加类".active"。然后在另一个500px向下滚动之后,第二个LI应该应用类"active",前一个LI应该删除类,依此类推。

JavaScript应该根据视口的高度计算像素,因为我并不总是知道页面有多高。

我知道这是可能的与jquery和一些(每个),但我不知道如何和从哪里开始。非常感谢任何帮助。: -)

.wrapper {
min-height: 2000px;
}
.header {
position: fixed;
width: 100%;
background: #eee;
right: 0;
left: 0;
top: 0;
}
ul {
position: relative;
list-style: none;
height: 35px;
margin: 0;
padding: 0;
}
li {
position: absolute;
visibility: hidden;
opacity: 0;
transition: all .2s ease;
transform: translateY(100%);
line-height: 35px;
margin: 0;
padding: 0 20px;
}
li.active {
transform: translateY(0);
opacity: 1;
visibility: visible;
}
<div class="wrapper">
  <div class="header">
    <ul class="list">
      <li>I wil lbe visible after a threshold of 500px</li>
      <li class="active">I should be visible when user has scrolled (pageheight - 500px / 4)</li>
      <li>I should be visible when user has scrolled (pageheight - 500px / 4) * 2 </li>
      <li>I should be visible when user has scrolled (pageheight - 500px / 4) * 3 </li>
    </ul>
  </div>
</div>

我做了这个小例子来演示这个标记:https://jsfiddle.net/a1hq5tg3/2/

您可以使用本地浏览器事件来检查当前滚动位置,并根据滚动范围更新所需的"li"

window.onscroll = function(args) {
   console.log(document.body.scrollTop);
   if(document.body.scrollTop > 200 && document.body.scrollTop < 300) {
      document.getElementsByClassName('active')[0].className.replace('active', '');
      document.getElementsByTagName('li')[next].className += ' active';
   }
};

我的回答是@VadimB和我的评论/回答的结果。

$(window).on('scroll', function() {
  var windowSize = $(window).scrollTop(),
    documentSize = $(document).height() - $(window).height();
  $('li').removeClass('hello');
  if (windowSize < (documentSize) * 0.25) {
    $('li').removeClass('hello');
  } else if (windowSize < (documentSize) * 0.50) {
    $('li:nth-child(2)').addClass('hello');
  } else if (windowSize < (documentSize) * 0.75) {
    $('li:nth-child(3)').addClass('hello');
  } else if (windowSize > (documentSize) * 0.75) {
    $('li:nth-child(4)').addClass('hello');
  }
});

小提琴:https://jsfiddle.net/randomobject/43sspmL5/