DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> jQuery元素滾動到頂部固定
jQuery元素滾動到頂部固定
編輯:JQuery特效代碼     
體驗效果:http://hovertree.com/texiao/jquery/25/

最近浏覽網頁時看到一個比較不錯的做法,就是網頁的某一塊在隨浏覽器滾動快要消失的時候會浮動在頁面上,頁面還可以繼續往上翻滾,但比較突出的那一塊一直貼在浏覽器的頂部,比如頂部導航條就可以用這種效果,自我感覺這種效果還是比較貼心的,於是乎自己鑽研了下,也寫了這樣一種效果,現在將代碼貼在下面和大家分享。

完整代碼:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery元素滾動到頂部固定 - 何問起</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base target="_blank" />
<script type="text/javascript" src="http://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
<style>
body {
margin: 0px;
font-family: Arial;
}

a {
color: blue;
}
</style>
</head>
<body>
<div style="text-align:center;width:100%;margin:0px auto;">
<h1>何問起</h1>
jQuery元素滾動到頂部固定 <br />固定在網頁頂部跟隨滾動條滑動而滑動的DIV層<br />請滾動頁面...<br />
<a href="http://hovertree.com/texiao/yestop/">Yestop</a> <a href="http://hovertree.com/h/bjaf/hoverclock.htm">HoverClock</a> <a href="http://hovertree.com">首頁</a>
<a href="http://hovertree.com/texiao/">特效</a>
<a href="http://hovertree.com/h/bjaf/jqguding.htm">原文</a>
</div>
<div style="height: 360px;background-color: #66FF66;text-align:center;">
</div>
<div style="width:100%;text-align:center;height:200px;background-color:skyblue" id="divhovertree">&copy; hovertree.com</div>
<div style="height: 200px; visibility: visible; background-color: Olive">
</div><div style="height:200px;background-color:burlywood"></div><div style="height:200px;background-color:darkorchid"></div>
<div style="height: 200px; visibility: visible; background-color:gray">
</div>
<div style="height:200px;background-color:blue"></div>
<div style="height:200px;background-color:red"></div>
<div style="height:200px;background-color:yellow"></div>
<div style="height:200px;background-color:yellowgreen"></div>
<div style="height:800px;background-color:white"></div>
<script type="text/javascript">
/*
*滾動條滑動,位置不變的DIV層
*div_id:DIV的ID屬性值,必填參數
*offsetTop:滾動條滑動時DIV層距頂部的高度,可選參數
*/
function fixDiv(div_id, offsetTop) {
var Obj = $('#' + div_id);
//判斷元素是否存在 何問起
if (Obj.length != 1) { return false; }

var offsetTop = arguments[1] ? arguments[1] : 0;
var ObjTop = Obj.offset().top;


$(window).scroll(function () {
if ($(window).scrollTop() <= ObjTop) {
Obj.css({
'position': 'relative',
"top": 0
});
} else {
Obj.css({
'position': 'fixed',
'top': 0 + offsetTop + 'px',
'z-index': 10
});
}
});
}
fixDiv('divhovertree', 5);//頂端浮動並於頂端保持5px的間距
</script>
</body>
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved