Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

css - Position fixed menu to top

I know how to use position:fixed; but I want, if the page scrolls over it, that it's on the top and on normal state lower.

.menu {
    height: 30px;
    width: 100%;
    border-bottom: 1px solid black;
    position: fixed;
    top: 0px;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understand correctly, you want to make a menu fixed after it's scrolled past? If that's the case, see this question.

If that doesn't work for you, consider using code like this, assuming jQuery (actually Sprint but it's about the same for both):

var navigation = $('nav').item(0);
var navigationY = navigation.element.offsetTop;
var navClone = navigation.clone();

$(window).bind('scroll', function() {
    var scrollY = (window.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop) >>> 0;
    if(scrollY > navigationY) {
        if(!navClone.element.parentNode || navClone.element.parentNode.nodeType !== 1) {
            navigation.after(navClone);
            navigation.addClass('fixed');
        }
    } else if(navClone.element.parentNode) {
        navClone.remove();
        navigation.removeClass('fixed');
    }
});

which I used in a recent project, so just change $('nav') at the top to whatever you need to select your element, e.g. $('.menu').


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...