javascript - 当我向下滚动页面时,如何让不同的背景图像亮起?
问题描述
我计划将六张不同的图像设置为固定的背景图像,并且我希望当我向下滚动页面时,不同的图像会在不同的时间亮起。但到目前为止,即使只是让背景图像显示出来,我也遇到了麻烦。到目前为止,我计划在 styles.css 中设置其中的六个:
#background1 {
background-image: url(img/background1.png);
background-size: auto;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: left;
}
但是没有一个出现,我不知道为什么。文档的其余部分也没有太多其他内容,包括 html 和 css 文档。
同样在我设法将背景图像放置到位之后,我是否会在滚动时使用 Javascript 来控制图像的照明/调光?我正在考虑类似的事情,但我不确定它是否会起作用:
$(function() {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$(‘body’).addClass(‘dimBackground’)
}
if ($(this).scrollTop() < 100) {
$(‘body’).removeClass(‘dimBackground’)
}
});
});
如果这是一个愚蠢的问题,我真的很抱歉,因为我对所有这些都是新手,所以只为提问而做了一个帐户。非常感谢!
解决方案
您的 CSS 可能有问题,但我无法确定,因为您没有共享所有内容。根据我的经验,您可能会在弄乱 body 标签时遇到麻烦。尝试使用 div 并跟踪其滚动。
这应该让你开始:
$("#content").scroll(function() {
if ($(this).scrollTop() > 100) {
$("#bg").css(
"background-image",
"url(https://images.unsplash.com/photo-1558980664-10e7170b5df9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60)"
);
} else {
$("#bg").css(
"background-image",
"url(https://images.unsplash.com/photo-1583369105090-c94b8c87e589?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60)"
);
}
});
body {
margin: 0;
padding: 0;
}
#bg {
position: fixed;
width: 100vw;
height: 100vh;
background-position: center;
background-size: cover;
background-image: url(https://images.unsplash.com/photo-1583369105090-c94b8c87e589?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60);
}
#content {
position: absolute;
overflow: scroll;
height: 100vh;
width: 100vw;
}
#largecontent {
height: 200vh;
color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bg"></div>
<div id="content">
<div id="largecontent">this div is just to force the content div to scroll</div>
</div>
此外:不要总是自己发明一切。您可能需要检查一些库来了解这个:bounds.js 用于滚动,animate.css 用于效果。
另外:不要忘记预加载图像,因此当用户到达滚动点时它们已经加载。
推荐阅读
- javascript - 我如何在 react.js 中像一堆卡片一样显示上传的照片?
- javascript - Angular7:服务工作者没有按预期运行
- mysql - 如何在mysql中的varchar变量中进行自动递增
- sql - 看不懂结果
- javascript - 不使用反应状态时对表数据进行排序
- php - Laravel 5.7 gRPC 集成
- javascript - React Tutorial 历史地图(step、move)
- autodesk-forge - Autodisk BIM360 Account Admin 端点是否支持三腿令牌?
- python - 从同一页面中的多个表单获取用户输入
- python - 具有 5 个未知参数的最小二乘函数