2010-01-13 56 views

回答

0

jQuery的一天節省...又來了!

CSS:

#wrapper { 
    position: absolute; 
    width: 200px; 
} 

#fancyDiv { 
    position: absolute; 
    top: 0; 
} 

#fancyDivt.fixed { 
    position: fixed; 
    top: 0; 
} 

HTML:

<div id="commentWrapper"> 
    <div id="comment"> 
    <p>some text</p> 
    </div> 
</div> 

的jQuery:

$(document).ready(function() { 
    $(function() { 
     var top = $('#fancyDiv').offset().top - parseFloat($('#fancyDiv').css('margin-top').replace(/auto/, 0)); 
     $(window).scroll(function (event) { 
       // what the y position of the scroll is 
       var y = $(this).scrollTop(); 

       // whether that's below the div 
       if (y >= top) { 
       // if so, ad the fixed class 
       $('#fancyDiv').addClass('fixed'); 
       } else { 
       // otherwise remove it 
       $('#fancyDiv').removeClass('fixed'); 
       } 
     }); 
    } 
}); 
1

在第二個示例中,他們使用jQuery來執行此操作。窗口對象的滾動事件捕獲和使用animate()函數動態地改變div的位置。