我想让我的菜单消失,并在我滚动时图像到达屏幕顶部时发生一些其他操作。图像是全宽的,因此它们覆盖了 x 轴上的每个点。我试过使用 elementFromPoint,但这只会返回整个 html 文档。我有什么办法可以做到这一点吗?
最佳答案
假设您的图像是固定的(我认为是),那么您可以这样做:
var timer;
$(document).scroll(function () {
// Set a timeout so that the function doesn't
// execute at every scroll event.
// Only when the user has actually stopped scrolling
if(timer) clearTimeout(timer);
timer = setTimeout(function () {
if($('#hello').offset().top - $(window).scrollTop() <= 0) {
$('#hello').attr('alt', 'Im touching the top!');
$('#status').text('Image is touching the top, or past it');
} else {
$('#hello').attr('alt', 'Not at top');
$('#status').text('Image is not touching the top');
}
}, 100);
});
html, body {
height: 400%;
}
img {
position: absolute;
top: 150px;
width: 100px;
height: 100px;
}
#status {
position: fixed;
top: 0;
right: 0;
background: #000;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="status">Image is not touching the top</div>
<img id="hello" alt="I'm an image">
关于javascript - 如何判断图像是否触及屏幕顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29980374/