lit*_*man 0 html javascript css jquery scrolltop
所以我像这样使用 jQuery 脚本;
$(window).scroll(function(){
$(".element").css("opacity", 1 - $(window).scrollTop() / 700);
});
Run Code Online (Sandbox Code Playgroud)
隐藏绝对定位的 flexbox 元素,因为它滚动到页面顶部之外。我在页面下方还有其他内容,我想对其应用相同的规则集;我希望它们在页面底部可见时保持 100% 不透明度,然后在用户滚动时让它们淡出,但这似乎只适用于最初显示在窗口中的第一个元素。我不确定为什么会这样 - 我已经尝试过这个700值,但对于页面下方的元素来说,它似乎永远不准确。
我正在做的内容是文本和图像。我认为这可能无法以我希望的方式实现 - 如果我能让它工作,理想情况下,文本块会从顶部到底部淡出,而不是一次淡出整个元素,但我明白用这种方法可能是不可能的。
我建议您为所有打算淡入淡出行为的元素使用一个公共类。您也可以使用选择器的组合。您实现的主要问题是您只能监听视口的滚动位置,而忽略了页面上不同元素与文档顶部的垂直距离不同这一事实。您将不得不计算元素相对于视口顶部的位置。
因此,要做到这一点,您必须:
在下面的概念验证示例中,我有:
$(window).scroll(function() {
// Setting: Start fading halfway up the page
var startPos = 0.5;
// Cache window object
var $w = $(window);
// Basically, we go through each element and check its relative position within the viewport
$('.scrollFade').each(function() {
// Get current relative position in viewport, based on the top edge
var pos = $(this).offset().top - $w.scrollTop();
// Get viewport height
var vh = $w.height();
if (pos < vh * startPos) {
// If element has past the starting threshold, we fade it
$(this).css('opacity', pos / (vh * startPos) * 1);
} else {
$(this).css('opacity', 1);
}
});
});Run Code Online (Sandbox Code Playgroud)
.textblock {
position: absolute;
display: flex;
flex-direction: column;
justify-content: flex-end;
bottom: 0px;
}
.extratext {
margin-top: 500px;
}
div {
height: 100vh;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="textblock scrollFade">
hey hey hey!
</p>
</div>
<div>
<p class="extratext scrollFade">
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum
et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
1.10.32.
</p>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2790 次 |
| 最近记录: |