2015年9月24日 星期四

特定位置浮動Element效果(jQuery)

今天要介紹的使用jQuery來製作"特定位置浮動Element效果"。

首先先看一下影片演示:

其中的紅色框框,我們希望在卷軸往下拉、越過紅色框框時紅色框框能夠停留在上方,而卷軸往上拉回去時,紅色框框能夠回到原位。

這樣的效果常被用在網站的選單上面,讓使用者瀏覽網站時,能夠一直都看得到選單。

程式實現的邏輯是這樣的:
  1. 先取得紅色框框的位置。
  2. 當卷軸滑動時,計算卷軸是否滑超過等於卷軸的位置。
  3. 如果超過的話,固定紅色框框的位置,將其z-index提高,為了避免下面的元素補上來,先製作一個假的、但透明看不見的紅色框框再固定原紅色框框;否則,不固定紅色框框的位置。將假的紅色框框刪掉。

下面上程式碼:
1. html部份:
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
<div class="bar">
This is the div class, top_tab_bar_bg.
</div>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
2. CSS部份:
body{
    height : 1000px;
}

.bar{
    width : 300px;
    border-style:solid;
    background-color: red;
}

3.javascript部份:
 //offset().top 是相對於文檔的偏移量,不會因為滾動卷軸而有變化。
    //CSS裡的top屬性在position為fixed時,是對應到相對於所處螢幕的偏移量
    //,會因滾動卷軸而有變化。
    var barOffsetTop = $(".bar:not(.tempBar)").offset().top;
 var barMarginTop = parseInt($(".bar:not(.tempBar)").css("margin-top"));
 
   $(window).scroll(function() {
     var scrollTopAmount= $(this).scrollTop();     
        //因為bar的position被設成fixed時會使下面的元素跑上來,所以做一個透明的tempBar來填充原來
        //bar的位置
     if (scrollTopAmount >= barOffsetTop){
            //如果卷軸拉超過bar的原始offset.top(),將bar固定住
            //如果沒有tempBar,做一個tempBar
      if ($(".tempBar").length == 0){
       $(".bar").clone().addClass('tempBar').insertAfter(".bar").css({"opacity":"0","z-index":"auto"});
      }      
      $(".bar:not(.tempBar)").css({ "position": "fixed", "top": "-"+barMarginTop+"px" , "z-index" : "999"});
     }else{
            //如果卷軸拉沒有超過bar的原始offset.top(),將bar的css還原,刪除tempBar
      $(".tempBar").remove();
      $(".bar:not(.tempBar)").css({ "position": "static" , "z-index" : "auto"});
     }
   });

線上看成品:
http://jsfiddle.net/a33e97cg/

2015年9月2日 星期三

好用 jQuery 外掛

 各種jQuery外掛庫的搜尋網站:

  1. jQuery plugins

覺得好用的jQuery外掛:

  1. jQuery custom content scroller :為區塊加上滑動的側邊卷軸。
  2. fullPage.js:為網站增加上下滑動(section)及同section左右滑動(slide)的效果。