如何停止粘div重叠在页脚

  • 本文关键字:重叠 div 何停止 jquery
  • 更新时间 :
  • 英文 :


我已经从不同的博客复制代码到我的小提琴帐户。一切正常。当你向下滚动页面时,黄色条会粘在页面上,当你滚动到底部时,页脚会把黄色条推到上面,这完全没问题。但问题是,当我通过点击"添加"按钮添加文本框超过10到15次时,黄色栏重叠在页脚上,文本框在浏览器窗口的下面不可见。我想让页脚把黄色的粘条推高,即使它的高度或大或小。有人能帮我解决这个问题吗?

Demo在这里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++;
});

最新更新