如何显示单独的锂元素滚动基于窗口的高度
How to show individual li-elements on scroll based on window height
我正试图根据页面滚动的距离为我的每个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/
相关文章:
- jQuery调整大小函数只适用于窗口
- 如何相对于浏览器窗口定位DIV
- 阻止Jquery对话框内容的CSS应用于主窗口
- 获取相对于窗口的IFRAME位置
- 通过jQuery或Javascript应用于父窗口的外部css规则
- 在chrome上显示类似于关闭窗口时的firefox的警报消息.确认消息”;离开"或“;留在这个页面上&quo
- 我可以修复手机相对于屏幕的背景吗?(注意:不是窗口)
- 相对于窗口缩放CSS
- 动态下拉菜单相对于浏览器窗口的宽度显示
- 如何打开新窗口/选项卡,但专注于打开窗口
- 如何获得iframe相对于顶部窗口的位置's视口
- jQuery对齐方式-相对于浏览器窗口
- 在鼠标按下/触屏时获取相对于父窗口而不是视窗的位置
- 如何查找元素相对于浏览器窗口的坐标
- Windows 8应用程序等效于“;窗口&”;
- 节点.js电子预构建错误找不到模块“浏览器窗口”窗口 10
- 是否可以获取 dom 元素相对于父窗口的位置
- Chrome 扩展程序相对于当前窗口打开弹出窗口
- javascript函数(窗口){})(窗口)
- javascript改变主体ID(与css)相对于浏览器窗口大小动态