javascript - 如何判断图像是否触及屏幕顶部?

标签 javascript jquery css scroll

我想让我的菜单消失,并在我滚动时图像到达屏幕顶部时发生一些其他操作。图像是全宽的,因此它们覆盖了 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/

相关文章:

javascript - 禁用基于复选框状态的控件?

javascript - 读取 IFrame cookie

javascript - 占位符中的两种不同文本样式

javascript - 在turn.js中设置第一页是双页而不是单页?

javascript - 使用 Angular 和 JSON 填充下拉列表

jquery - 使用 jQuery 更改 html 内容时出错

jquery - div 在 IE8 中没有扩展到新内容

html - 下拉菜单 html css 不工作

css - 如何设置不影响背景图片的边框

javascript - 自动将 session 信息附加到 Sails.js 中的模型