現在常常能看到一些網站(如:新浪微博和花瓣)導航條或工具欄固定在網頁的頂部或其他地方。這樣的布局方式,能便於用戶點擊和“曝光率”,不用每次都要把網頁拖動到某個特定位置才能點擊或看到。
其實這樣的布局方式很早就有,只是沒有那么個契機推廣開吧。做起來也不復雜,只要設置一個小小的屬性“position:fixed”便能完成,最關鍵的無不呼在於要兼容IE6而已。
首先我們來看HTML代碼,是不是超簡單?這里提供的只是一個簡單的框架,實際應用的時候,只要把想要的元素添加東西就在這區域內加就行。
HTML CODE:
<
div
id
=
"header"
>Default header. No absolute and fixed.</
div
>
<
div
id
=
"topToolbar"
>Fixed at the top of the Toolbar.</
div
>
<
div
id
=
"content"
>
<
p
>此處省略1000字...</
p
>
</
div
>
<
div
id
=
"bottomToolbar"
>Fixed at the bottom of the Toolbar. By Bluesdream.com</
div
>
|
CSS CODE:
<style type=
"text/css"
>
/* 全局CSS*/
*{
margin
:
0px
;
padding
:
0px
;}
a{
text-decoration
:
none
;
outline
:
none
;}
a:hover{
text-decoration
:
underline
;}
/* 實例CSS */
html{
_background
:
url
(about:blank);}
/*阻止閃動 in IE6 , 把空文件換成about:blank , 減少請求*/
body{
font-size
:
12px
;
font-family
:
Arial
,
Tahoma
,
sans-serif
;
color
:
#EEEEEE
;
text-align
:
center
;
background
:
#E2E2E2
;}
#topToolbar{
_display
:
none
;
width
:
100%
;
height
:
40px
;
line-height
:
40px
;
background
:
#101010
;
border-bottom
:
2px
solid
#409F89
;
position
:
fixed
;
top
:
-40px
;
left
:
0
;
_position
:
absolute
;
_top
:
0
;
}
#bottomToolbar{
width
:
100%
;
height
:
40px
;
line-height
:
40px
;
background
:
#101010
;
border-top
:
2px
solid
#409F89
;
position
:
fixed
;
bottom
:
0
;
left
:
0
;
_position
:
absolute
;
_top
:expression(documentElement.scrollTop+documentElement.clientHeight-this.offsetHeight);
/*
document.body.scrollTop 網頁滾動的距離
document.body.clientHeight 網頁可見區域高
this.offsetHeight 當前元素的高度
*/
}
#bottomToolbar a{
color
:
#FFF
;}
#header{
width
:
100%
;
height
:
80px
;
line-height
:
80px
;
background
:
#101010
;
border-top
:
2px
solid
#409F89
;
}
#content{
width
:
880px
;
height
:
1390px
;
line-height
:
18px
;
text-align
:
left
;
margin
:
40px
auto
80px
auto
;
padding
:
30px
50px
;
background
:
#FFF
url
(images/scaleplate.png)
no-repeat
;
border
:
1px
solid
#CCC
;
}
</style>
|
JAVASCRIPT CODE:
<script type=
"text/javascript"
>
$(
function
(){
$(window).scroll(
function
() {
var
topToolbar = $(
"#topToolbar"
);
var
headerH = $(
"#header"
).outerHeight();
var
scrollTop = $(document).scrollTop();
//IE6 Expression方法和jquery animate方法同事使用會有問題,所以加個判斷,簡化下IE6下的顯示方式.
if
($.browser.msie && ($.browser.version ==
"6.0"
) && !$.support.style) {
if
( scrollTop >= headerH ){
topToolbar.show();
}
else
if
( scrollTop < headerH ){
topToolbar.hide();
}
}
else
{
if
( scrollTop >= headerH ){
topToolbar.animate({
'top'
:0 });
}
else
if
( scrollTop < headerH ){
topToolbar.animate({
'top'
:-40 });
}
};
});
});
</script>
|
如果要像新浪微博那樣,始終浮動固定在頂部,那JS部分就可以無視了,有沒有都無所謂,直接改CSS就行。
#topToolbar{
width
:
100%
;
height
:
40px
;
line-height
:
40px
;
background
:
#101010
;
border-bottom
:
2px
solid
#409F89
;
position
:
fixed
;
top
:
0
;
left
:
0
;
_position
:
absolute
;
_top
:expression(documentElement.scrollTop);
}
|