標籤:style blog io ar color os 使用 sp java
今天做了個固定定位的效果。比如對導航需要進行固定定位效果:當沒有滾動到導航下面,導航正常顯示。當滾動到導航下面,導航就固定到頂部。
這個效果使用了jquery的方法實現,具體思路為:1)首先擷取導航相對與文檔的位移量top(使用offset().top)2)定義滾動事件,擷取滾動元素的scrollTop,對scrollTop及top進行比較3)若scrollTop超過了top,則對導航進行position:fixed設定,若沒有超過,則對導航設定預設的position:static.
另外針對跳轉到固定位置,很多處理是通過錨點實現,location.href=#id或者location.hash=#id這種形式實現。其實也可以利用jquery的offset().top來達到同樣的效果,具體可以看下面代碼中針對固定定位元素的click事件的處理。
這裡寫了個demo:
<!doctype html>
<html>
<head>
<meta charset="utf8">
<title>jquery固定定位demo</title>
<style type="text/css">
body{margin:0;padding-top:100px;background-color:#fff;}
.content{width:500px;height:300px;background-color:#ccc;}
h2{padding:10px;background-color:#000;color:#fff;}
</style>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div class="floor">
<h2 class="fixed">第一樓</h2>
<div class="content">ddddd</div>
</div>
<div class="floor">
<h2>第二樓</h2>
<div class="content">ffff</div>
</div>
<div class="floor">
<h2>第三樓</h2>
<div class="content">sdfsf</div>
</div>
<div class="floor">
<h2>第四樓</h2>
<div class="content">aaaaaa</div>
</div>
<script type="text/javascript">
var fixed = $(".fixed");
var position = fixed.css("position");
var offsetTop = fixed.offset().top;
//定義滾動事件,判斷scrollTop及offsetTop
$(window).scroll(function(){
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if(scrollTop > offsetTop){
fixed.css({"position":"fixed","width":"100%","top":"0"});
}else{
fixed.removeAttr("style").css({"position":position,"width":"100%"});
}
});
//點擊固定元素,回到最初的位置
fixed.bind("click",function(){
if($(this).css("position") == "fixed"){
$(this).removeAttr("style").css({"position":"static","width":"100%"});
$(document).scrollTop(offsetTop);
}
});
</script>
</body>
</html>
---------------------------------------分割線----------------------------------------------------------
對clientWidth,offsetWidth,offsetTop,jquery的offset().top的解釋,因為本人對它們一直有點疑問:
clientWidth:元素的寬度,不包括border和scrollBar的寬度
offsetWidth:元素的寬度+ border+scrollBar的寬度
offsetTop:元素距離最近的一個設定了position不為static的父級元素的距離
jquery中的offset().top:元素距離文檔的距離。
jquery的固定定位效果