1 回答

TA贡献1852条经验 获得超7个赞
您尝试使用的 jQyery 代码存在一些问题:
1.你只是在页面加载时检查滚动位置 - 你需要不断检查滚动事件:
$(window).on('scroll', function( /* handler function */));
2.您试图通过 CSS 更改图像,但图像未使用 CSS 显示。相反,您可以像这样更改元素src
的:img
$(".image-test img").attr("src", imgUrl);
3.您没有检查页面内容元素的底部(替换图像将被换回的位置)。你可以这样得到它:
var contentTop = $(".page-content").offset().top; var contentBottom = contentTop + $(".page-content").outerHeight(true);
4.您需要检查滚动是否在这些位置之间:
if ( ($(this).scrollTop() > contentTop) && ($(this).scrollTop() < contentBottom))
为了使其具有响应性(例如,如果在页面加载后通过调整窗口大小更改屏幕大小,它将起作用),您还需要将其包含在滚动事件处理程序中。
功能的完整代码
// get the URL of the image so we can use it to swap back
defaultImgUrl = $(".image-test img").attr("src");
// check the scroll position on the scroll event
$(window).on('scroll', function() {
// get the top and bottom positions pf the page content
var contentTop = $(".page-content").offset().top;
var contentBottom = contentTop + $(".page-content").outerHeight(true);
// check if the scroll position is within the page content
if (($(this).scrollTop() > contentTop) && ($(this).scrollTop() < contentBottom)) {
// change the image url
$(".image-test img").attr("src", "https://lorempixel.com/output/nature-q-c-100-50-2.jpg");
} else {
$(".image-test img").attr("src", defaultImgUrl);
}
});
工作示例:
// get the URL of the image so we can use it to swap back
defaultImgUrl = $(".image-test img").attr("src");
// check the scroll position on the scroll event
$(window).on('scroll', function() {
// get the top and bottom positions pf the page content
var contentTop = $(".page-content").offset().top;
var contentBottom = contentTop + $(".page-content").outerHeight(true);
// check if the scroll position is within the page content
if (($(this).scrollTop() > contentTop) && ($(this).scrollTop() < contentBottom)) {
// change the image url
$(".image-test img").attr("src", "https://lorempixel.com/output/nature-q-c-100-50-2.jpg");
} else {
$(".image-test img").attr("src", defaultImgUrl);
}
});
.section1,
.section2,
.page-content {
height: 100vh;
}
.section1 {
background-color: green;
padding-top: 50px;
}
.section2 {
background-color: red;
}
nav {
height: 50px;
background-color: grey;
position: fixed;
width: 100%;
display: flex;
}
.image-test img {
width: 100px;
height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
<div class="image-test">
<img src="https://lorempixel.com/output/nature-q-c-100-50-5.jpg" alt="">
</div>
<div>
<p>Change me to a different picture once I reach the top of page content. Then change me back to the same picture as the one I had in the hero once I reach the footer.</p>
</div>
</nav>
<div class="section1" id="hero">
<h1>Hero</h1>
</div>
<div class="page-content">
<h1>Page Content</h1>
</div>
<div class="section2">
<h1>Footer</h1>
</div>
添加回答
举报