jQuery-如果div在窗口顶部,请添加类/样式? (粘性横幅) [英] jQuery - if div is at top of window, add class/style? (sticky banner)

查看:141
本文介绍了jQuery-如果div在窗口顶部,请添加类/样式? (粘性横幅)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我做了一个粘贴式横幅

So I've made a sticky banner

此处的示例: http://jsfiddle.net/zu60j5rr/

Example here: http://jsfiddle.net/zu60j5rr/

在示例中,它可以正常工作.但是,我要在其上使用的网站具有顶级导航,它在不同的浏览器中无法完全呈现相同的效果.因此,我不能依靠顶部"在所有浏览器中正常工作

In the example it works fine. But the site that I want to use it on has a top nav that doesn't quite render the same across different browsers. So I can't rely on "top" to work as it should across all browsers

所以我想知道的是.如果div击中了窗口的顶部,有什么办法可以添加类似的语句-添加样式以固定位置?然后,如果向后滚动,是否要删除样式?

So what I'm wondering is. Is there any way I can add a statement of something like, if the div hit the top of the window - Add style to fix the position? And then if it's scrolled back, remove the style?

下面是我目前所拥有的东西:

here's what I currently have, as fiddled:

$(document).on( 'scroll', function(){
        if ($(window).scrollTop() > 100) {
            $('#stickyBanner').css({position: "fixed", top: "0px"});
        } else {
            $('#stickyBanner').css({position: "relative", top: "0px"});
        }
    });

谢谢!

推荐答案

您可以稍微更改一下脚本,以便它可以检查粘性导航的offset top值是否大于或等于window scrollTop的值.基本上,如果它们相同/相等,则元素位于窗口顶部:)

You can change your script a little bit so it can check if the offset top value of the sticky nav is bigger or equal to the value of the window scrollTop. Basically if they are the same / equal the element is at top of the window :)

此处的示例 http://jsfiddle.net/zu60j5rr/1/

var stickyTop = $('#stickyBanner').offset().top;

$(window).on( 'scroll', function(){
        if ($(window).scrollTop() >= stickyTop) {
            $('#stickyBanner').css({position: "fixed", top: "0px"});
        } else {
            $('#stickyBanner').css({position: "relative", top: "0px"});
        }
    });

这篇关于jQuery-如果div在窗口顶部,请添加类/样式? (粘性横幅)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆