jQuery標題自動頂貼效果程式碼例項

admin發表於2017-04-15

拖動滾動條可以檢視效果,比較常見於移動端。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
*{
  padding:0;
  margin:0;
}
.title{
  height:40px;
  background-color:#cfc;
}
.titleBar{
  background-color:#ffc;
  height:30px;
  width:90%;
  text-align:center;
  line-height:30px;
  border-bottom:solid 1px #ccc;
  position:relative;
}
.titleBar.fixed{
  position:fixed;
  top:0;
}
.content{
   height:600px;
   background-color:#ccf;
}
.info{
  position:fixed;
  top:0;
  width:100px;
  height:100px;
  background-color:#ccc;
  z-index:10;
}
</style>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
$(function(){
  var titlePosition = [];
  $('.title').each(function(i,e){
    titlePosition.push($(e).offset().top);
  })
         
  $(window).on('scroll',function(){
    $('.info').text($(this).scrollTop());
    for(var i in titlePosition){
      if($(this).scrollTop() >= titlePosition<i>){
        $('.title').eq(i).find('.titleBar').addClass('fixed');
      }else{
        $('.title').eq(i).find('.titleBar').removeClass('fixed');
      }
    }
  })
})
</script>
</head>
<body>
<div class="pad">
  <div class="title">
    <div class="titleBar">1</div>
  </div>
  <div class="content"></div>
</div>
<div class="pad">
  <div class="title">
    <div class="titleBar">2</div>
  </div>
  <div class="content"></div>
</div>
<div class="pad">
  <div class="title">
    <div class="titleBar">3</div>
  </div>
  <div class="content"></div>
</div>
<div class="info"></div>
</body>
</html></i>

相關文章