如何用jQuery构建简单的粘性导航? [英] How to build simple sticky navigation with jQuery?

查看:98
本文介绍了如何用jQuery构建简单的粘性导航?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在滚动时更改div的css。这是我的代码,但不幸的是它不工作。

I'm trying to change the css of a div when scrolling. This is my code but unfortunately it won't work.

$(document).ready(function() {
   $(window).scroll(function () {
        if ($(this).scrollTop() > 150) {
            $('#subnav').css({
                'position' : 'fixed',
                'top' : '0'
            });
        } else {
            $('#subnav').css({
                'position' : 'static',
                'top' : 'auto'
            });
        }
    });
 });


推荐答案

尝试:

这里是工作jsFiddle

$(document).ready(function() {
   $(window).scroll(function() {
       var scrollVal = $(this).scrollTop();
        if ( scrollVal > 150) {
            $('#subnav').css({'position':'fixed','top' :'0px'});
        } else {
            $('#subnav').css({'position':'static','top':'auto'});
        }
    });
 });

注意:如果您只有一个值,可以使用 else ,但如果你有多个值我建议不使用 else ,因为它创建冲突,使用 else if intead。

Note: If you have just one value you can use else, but if you have multiple values i suggest to not use else, because it creates conflict, use else if intead.

这篇关于如何用jQuery构建简单的粘性导航?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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