如何阻止粘性div在页脚上重叠?

问题描述:

我已将不同博客的代码复制到我的小提琴帐户。一切工作正常。当您向下滚动页面时,黄色条会粘在页面上,当您滚动到底部时,页脚将向上推动黄色条,这是绝对好的。但问题是,当我通过单击“添加”按钮添加文本框超过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++; 
    }); 
}); 

的主要问题阻止您预期的结果是你的代码是利用初始计算栏的高度,而不是每一个滚动事件中获得更新的高度。

$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