如何“固定"菜单只有当它到达顶部时? [英] How to "fixed" menu only when it get to the top?

查看:103
本文介绍了如何“固定"菜单只有当它到达顶部时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望固定我的顶部菜单并滚动页面,但仅当它到达屏幕顶部时才可以. 像这儿: http://en.miui.com/forum.php

I want my top menu to be fixed and scroll with the page, but only when it get to the top of the screen. Like here: http://en.miui.com/forum.php

有人知道吗?

tnx:)

推荐答案

要么将CSS的position:sticky与浏览器供应商前缀一起使用,要么在元素触及窗口顶部,scrollTop或比其大的任何元素时检查窗口的scrollTop它,以固定的位置固定元素.

Either uses CSS' position:sticky with browser vendor prefixes or check the window's scrollTop when the element touches the top of the window and at the scrollTop or anything larger than it, fix the element with fixed positioning.

在滚动时,当scrollTop较小时,为其指定相对位置.

On scroll, when the scrollTop is less, give it relative positioning.

在jQuery中:

$(window).on('scroll', function(){
    // instead of 180 use the scrollTop when the element touches the top of the window
    if($(window).scrollTop()>=180){
        $(element).css('position', 'fixed');
    }
    else $(element).css('position', 'relative');
});

要检查要使用的数字(而不是180),请滚动到元素触摸顶部的位置,进入开发人员控制台,然后键入$(window).scrollTop(),这应该会为您提供所需的数字.

To check the number you want to use instead of 180, scroll to the point where the element touches the top, go into the developer console and type $(window).scrollTop() this should give you the number you are looking for.

这篇关于如何“固定"菜单只有当它到达顶部时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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