JS-實作導覽列懸停
先佈個局:
新增簡單的樣式:
div.main{
寬度:800px; #CCC;
邊距:10px 自動0;
位置:相對;
}
div.content{
寬度:800px;
高度:400px
寬度:800px;
高度:400px
寬度:800px;
高度:400px; >背景:黃色;
邊距:10px 自動 0;
}
div.navigation{
寬度:800px;
高度:40px;
背景:紅色;
邊距:4px 自動0;
頂部:400px;
左:0px;
位置:絕對;
}
div.tab{
寬度: 195px;
高度:40px;
背景:藍色;
浮動:左;
左邊距:5px;
}
程式碼如下:
//記錄導覽列原來在頁面上的位置
var naviga_offsetTop = 0;
//IE7不辨識getElementsByClassName,為了相容自訂一個
function mygetgetsByClassName( ) {
var el = [];
//取得所有元素
_el = document.getElementsByTagName('*');
//透過className刷選
for (var i= 0; i<_el.length i>if (_el[i].className == class_name ) {
el[el.length] = _el[i];
}
}
return el;
}
//導覽條,懸停在頂部
function naviga_stay_top(){
var a_navigation_bar = [];
if(docment.Elementp. ){//Chrome, FF
a_navigation_bar = document.getElementsByClassName("navigation");
} else {//IE
a_navigation_bar = my_getElementsByClassName("igation"); scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
if( scrollTop > naviga_offsetTop){
a_navigation_bar[0].style.top =offsetTop){
a_navigation_bar[0].style.top = scrollT" {
a_navigation_bar[0].style.top = naviga_offsetTop "px";
}
}
//給導覽列上四個tab,加上點擊事件。
window.onload=function(){
var a_tabs = [];
if( document.getElementsByClassName ){//Chrome, FF
a_tabs = document.getElementsByClassName("tab""); 🎜>}else{ //IE
a_tabs = my_getElementsByClassName("tab");
}
var a_contents = [];
if( document.getElementsByClassName )//C4m. FF
a_contents = document.getElementsByClassName("content");
}else{//IE
a_contents = my_getElementsByClassName("content");
}
a_tab .onclick=function(){
window.scrollTo(0, a_contents[2].offsetTop);
}
a_tabs[1].onclick=function(){
window.scrollTo(0 , a_contents[3].offsetTop);
}
a_tabs[2].onclick=function(){
window.scrollTo(0, a_contents[4].offsetTop);
}
}
a_tabs[3].onclick=function(){
window.scrollTo(0, a_contents[5].offsetTop);
}
//取得頁面上,導覽列到頂部的位置
var a_navigation_bar = [];
if(document.getElementsByClassName){//Chrome, FF
a_navigation_bar = document.getElementsByClassName("navigation");
document.getElementsByClassName("navigation"); a_navigation_bar = my_getElementsByClassName("navigation");
}
naviga_offsetTop = a_navigation_bar[0].offsetTop;
//給滾動條以及滑鼠滑鼠滑鼠圖>加上滑鼠// document.onmousewheel= naviga_stay_top;
if( window.attachEvent) //IE
{
window.attachwindow( attachEvent("onscroll", naviga_stay_top);
document.attachEvent("onmousewheel", naviga_stay_top);
document.attachasEvent("onscroll", nav_stay_top) document.attachasEvent("onscroll", Higa_stay_top) window.addEventListener("mousewheel", naviga_stay_top,false);
window.addEventListener("scroll", naviga_stay_top,false);
documigai_s,fore );
document.addEventListener("scroll", naviga_stay_top,false);
}
}
不知道什麼原因,在IE下,滾動條或者滑鼠滾輪的時候,導覽列會抖動;而在Chrome和FF上有沒有任何問題。還望高人指點。