如何实现自动隐藏导航?

时间:2013-08-03 18:22:03

标签: web responsive-design

我不确定在哪里发布这个问题,所以如果我违反了任何政策,请原谅。

为了澄清我的问题,我想要实现与Teehan + Lax相同的导航栏。

以下是他们的网站:http://www.teehanlax.com/tools/

如果您注意到,向下滚动时导航会自动隐藏,但是当您向上滚动时,会再次显示自己。

所以我的问题是,他们是如何实现这一目标的?是仅通过CSS还是我需要JavaScript来执行此操作?无论它是什么方式,有人也可以指出如何找到实现这一点的信息的正确方向吗?

谢谢

1 个答案:

答案 0 :(得分:7)

不可能像你想要的那样在纯CSS中将位置从固定更改为绝对,所以我使用了一些javascript来执行此操作。 Demo

function followTo(elem, pos) {
    var element = document.getElementById(elem);        
    window.onscroll = function(e){
        var disFromTop = document.all? iebody.scrollTop : pageYOffset;
        if (disFromTop > pos) {
            element.style.position = 'absolute';
            element.style.top = pos + 'px';
        } else {
            element.style.position = 'fixed';
            element.style.top = 0;
        }
    };
};    
followTo("nav", 100);

它甚至包括从this SO post拉出的IE修复,以获得正确的滚动位置

Here is the jQuery version取自this SO post

修改

正如zanona所指出的,如果您从页面中的更下方向上滚动,我没有包含导航显示的功能。因此,我创建了一种使用setInterval

的新技术
var last = 0,    // The last read top value
    delay = 150, // The delay for the setInterval
    threshold = 30;    // The max scroll distance before showing/hiding the nav

//I always set a variable to my setIntervals in case I want to stop them later on
var navMovement = setInterval(function() {
    var nav = document.getElementById('nav'), // Gets nav object
        pageVertOffset = document.all? iebody.scrollTop : pageYOffset;
    // Happens if the difference in scroll is below the negative threshold
    if(pageVertOffset - last < -threshold) { 
        nav.style.top = "0px"; // Put the nav at the top of the window
    }
    // Happens if the difference in scroll is above the threshold
    else if(pageVertOffset - last > threshold){ 
        nav.style.top = - nav.offsetHeight + "px"; // Hides the navigation
    }
    last = pageVertOffset; // Updates the previous scroll value
}, delay); // Runs every `delay` amount

Javascript version,或者如您所愿,jQuery version

我以为我很好地重建了这个网站(但它更好,因为我有一只小猫,哈哈)