Html 固定内容滚动布局
下面的站点在每个部分中使用固定的背景图像,但是如何在每个部分中添加固定内容(文本、图像)并保持相同的滚动效果? 看看我的例子,更好地了解我想要什么: 我的尝试:Html 固定内容滚动布局,html,css,scroll,fixed,Html,Css,Scroll,Fixed,下面的站点在每个部分中使用固定的背景图像,但是如何在每个部分中添加固定内容(文本、图像)并保持相同的滚动效果? 看看我的例子,更好地了解我想要什么: 我的尝试: #wrapper { position: relative; height: 500px; width: 500px; overflow: scroll; } .section { position: relative; height: 100%; width: 100%; }
#wrapper {
position: relative;
height: 500px;
width: 500px;
overflow: scroll;
}
.section {
position: relative;
height: 100%;
width: 100%;
}
.content {
position: fixed;
}
#s1 {
background-color: #f00;
}
#s2 {
background-color: #0f0;
}
#s3 {
background-color: #00f;
}
#s1 .content {
}
#s2 .content {
margin-top: -400px;
}
#s3 .content {
margin-top: -800px;
}
<div id="wrapper">
<div class="section" id="s1">
<div class="content">hello1</div>
</div>
<div class="section" id="s2">
<div class="content">hello2</div>
</div>
<div class="section" id="s3">
<div class="content">hello3</div>
</div>
</div>
#包装器{
位置:相对位置;
高度:500px;
宽度:500px;
溢出:滚动;
}
.科{
位置:相对位置;
身高:100%;
宽度:100%;
}
.内容{
位置:固定;
}
#s1{
背景色:#f00;
}
#s2{
背景色:#0f0;
}
#s3{
背景色:#00f;
}
#s1.内容{
}
#s2.内容{
利润上限:-400px;
}
#s3.内容{
利润上限:-800px;
}
你好
你好
你好
我想要的是:
第一部分(红色)应仅显示“hello1”
第二个(绿色)只有“hello2”
参考站点的第三个(蓝色)唯一的“hello3”仅使用
背景图像
设置为固定
,如下所示:
更新
好的,我明白了。您需要使用jquery和$(窗口)执行类似操作。scroll()
函数:
使用
position:fixed
只是将元素从文档流中分离出来,它不能被父元素包含,因此您需要使用absolute
并基于scrollTop
对其进行定位,以使其看起来是固定的。可能是这样的吗?有点黑,但如果您设置了截面高度,则会执行以下操作:
$(document).ready(function(){
$('.div3').hide();
$('.div2').hide();
$('.div1').show();
$('#wrapper').scroll(function(){
console.log($('#wrapper').scrollTop());
if($('#wrapper').scrollTop() > 945){
$('.div3').show();
$('.div2').hide();
$('.div1').hide();
}
else if ($('#wrapper').scrollTop() > 465) {
$('.div3').hide();
$('.div2').show();
$('.div1').hide();
}
else {
$('.div3').hide();
$('.div2').hide();
$('.div1').show();
}
});
});
更新小提琴:
这样,您还可以修改“hello1/hello2/hello3”的位置,使其位于相同的位置,而不是不同的位置。或者您可以只使用一个div,根据滚动位置修改/替换hello1/hello2/hello3中的文本。希望这有帮助 您还可以设置网页的高度,然后在上下滚动时显示div。 以下是一个工作示例:
$(文档)。滚动(函数(){
var y=$(this.scrollTop();
如果(y>0&&y<400){
$('#s1').fadeIn();
$('#s3').fadeOut();
$('#s2').fadeOut();
}否则,如果(y>400&&y<800){
$('#s1').fadeOut();
$('#s2').fadeIn();
$('#s3').fadeOut();
}如果(y>800),则为else{
$('#s3').fadeIn();
$('#s2').fadeOut();
}
});
滚动一定数量的像素后,div将开始出现并相互替换
您可以通过在css中设置身体高度来更改
y
的值,如小提琴所示。然后,您可以将jQuery中的像素条件设置为您喜欢的任何设置。谢谢您的快速回答,但我想您不明白我的问题:我要求正确显示文本:第一张图像上只有hello1,第二张图像上只有Hello2……很好,谢谢!:D如果没有其他答案,我会接受你的答案。@bonell96没问题。很高兴为您提供帮助。谢谢,但是使用您的方法,整个内容只是在某个位置弹出,而不是一直在那里,只是被覆盖。示例:假设我在内容中放置了一个带有的图像,您的示例只能在某个位置显示整个图像,而覆盖效果将不起作用。我希望我能解释我自己。不完全是我想要的,但它有一个很酷的效果。谢谢你的提示!:)
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 0 && y < 400) {
$('#s1').fadeIn();
$('#s3').fadeOut();
$('#s2').fadeOut();
} else if (y > 400 && y < 800) {
$('#s1').fadeOut();
$('#s2').fadeIn();
$('#s3').fadeOut();
}else if (y > 800) {
$('#s3').fadeIn();
$('#s2').fadeOut();
}
});