在 jQuery 中已經有包裝好的函式 scrollTop() 和 scrollLeft(),可以簡單地做到偵測的動作。
例如我想做的是當捲軸往下捲到選單會看不見的時候,就要自動把選單往下挪動。
實作方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 |
$(window).scroll( function () { // Get the position of the current scroll. var top_position = $( this ).scrollTop(); if ( top_position > 144){ // Let the item move with scrolling. $( "#menu" ).css( "top" , (top_position-86) + "px" ); } else { // Reset the position to default. $( "#menu" ).css( "top" , "48px" ); } }); |
第 5 行在檢查,如果捲軸捲到 144px 或更下面的位置時(距離視窗頂端 144px)
就去修改 ID 為 menu 的元件,把 top 屬性的 px 值依照目前捲軸的位置做調整,以讓這個元件一直跟著捲軸跑。
而當捲軸回到比較上面的位置時,為了避免元件跑過頭,在第 8 行開始就設定讓捲軸回到初始位置。
參考資料:
1、[jQ]用 jQuery 控制網頁捲軸移動
沒有留言:
張貼留言