這是不可能改變位置從固定到絕對純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);
它甚至還包括一個IE修復從this SO post拉到得到正確的滾動位置
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
我以爲我重新創建該網站相當不錯(但它是更好,因爲該礦擁有一隻小貓,哈哈)
嗯,我只是發現了一些酷酷的ASCII藝術他們的一些真棒小JavaScript。 – BLaZuRE