2013-02-28 64 views
0

我已將不同博客的代碼複製到我的小提琴帳戶。一切工作正常。當您向下滾動頁面時,黃色條會粘在頁面上,當您滾動到底部時,頁腳將向上推動黃色條,這是絕對好的。但問題是,當我通過單擊「添加」按鈕添加文本框超過10到15次時,黃色欄與頁腳重疊,文本框在瀏覽器窗口內下方,並且不可見。我希望頁腳能夠將黃色的粘貼條向上推,即使它的高度小或大。任何人都可以幫我解決這個問題?如何阻止粘性div在頁腳上重疊?

Demo is here http://jsfiddle.net/awaises/k7xfc/

jQuery的

$window = $(window), 
$sidebar = $(".sidebar"), 
sidebarTop = $sidebar.position().top, 
sidebarHeight = $sidebar.height(), 
$footer = $(".footer"), 
footerTop = $footer.position().top,  
$sidebar.addClass('fixed'); 

$window.scroll(function(event) { 
scrollTop = $window.scrollTop(), 
topPosition = Math.max(0, sidebarTop - scrollTop), 
topPosition = Math.min(topPosition, (footerTop - scrollTop) - sidebarHeight); 
$sidebar.css('top', topPosition); 
}); 

$(document).ready(function() { 
var counter = 2; 
$("#addButton").click(function() { 

     $('<div/>',{'id':'TextBoxDiv' + counter}).html(
      $('<label/>').html('Textbox #' + counter + ' : ') 
     ) 
     .append($('<input type="text">').attr({'id':'textbox' + counter,'name':'textbox' + counter})) 
     .appendTo('#TextBoxesGroup')  
     counter++; 
    }); 
}); 

回答

0

的主要問題阻止您預期的結果是你的代碼是利用初始計算欄的高度,而不是每一個滾動事件中獲得更新的高度。

$window.scroll(function (event) { 
    var scrollTop = $window.scrollTop(); 
    var topPosition = Math.max(0, sidebarTop - scrollTop); 

    // Ensure you are using the current sidebar height and not the initial height 
    topPosition = Math.min(topPosition, (footerTop - scrollTop) - $sidebar.height()); 

    $sidebar.css('top', topPosition); 
}); 

我推薦另一項建議是,你觸發addButton單擊處理過程中窗口滾動處理程序,以確保您做出適當的調整,你要添加的項目。

$("#addButton").click(function() { 
    $('<div/>', { 
     'id': 'TextBoxDiv' + counter 
    }).html(
    $('<label/>').html('Textbox #' + counter + ' : ')) 
     .append($('<input type="text">').attr({ 
      'id': 'textbox' + counter, 
      'name': 'textbox' + counter 
    })).appendTo('#TextBoxesGroup'); 

    // Trigger the scroll handler to ensure the sidebar is properly positioned 
    $window.triggerHandler('scroll'); 

    counter++; 
}); 

DEMO

+0

魯本,感謝您的建議。我看起來很棒。我必須在ASP.NET項目上應用此功能。我希望,不會有更多的問題來實現這一點。如果我需要進一步的幫助,我可以回電嗎? – 2013-02-28 15:09:59

+0

@ user1356607很高興幫助。如果您發現需要更多幫助,我會建議在SO上創建一個新問題。在這一點上,您可以獲得其他社區的幫助。一旦你這樣做,你總是可以在這裏回覆並留下新問題的鏈接,以便我得到通知。 – 2013-02-28 21:57:12