一旦到达其父容器的底部,我怎么能在“#sidebar”中添加一类“底部”?

我正在使用下面的代码,一旦它从站点的顶部到达某个高度,它会添加一个fixed#sidebar的类,具体取决于它所在的页面(即主页,单页,页面)。

以类似的方式,一旦#sidebar到达其容器的底部( #content ),我想在#sidebar添加一类bottom 。 如果用户向上滚动,则应删除bottom类,并应添加fixed类。

目标是尝试使固定侧边栏一旦到达其底部就与其容器中的其余内容一起向上移动。

JavaScript的

 var threshold = 236; if (jQuery(document.body).hasClass("home")) { threshold = 654; } else if (jQuery(document.body).hasClass("single") || jQuery(document.body).hasClass("page")) { threshold = 20; } var scrolled = false; jQuery(window).scroll(function () { if (jQuery(window).scrollTop() >= threshold && !scrolled){ jQuery('#sidebar').addClass('fixed'); scrolled = true; } else if (jQuery(window).scrollTop() < threshold && scrolled) { jQuery('#sidebar').removeClass('fixed'); scrolled = false; } }); 

HTML

 

我相信这是你想要做的?

http://jsfiddle.net/M5sMx/33/

 $(window).on("scroll", function() { // When you scroll the window, do this function updatePosition(); }); var tester = null; function updatePosition() { var sidebar = $("#sidebar"); // Set #sidebar to a variable called "sidebar" if (tester == undefined) { // Create a tester div to track where the actual div would be. // Then we test against the tester div instead of the actual div. tester = sidebar.clone(true).removeAttr("id").css({"opacity" : "0" }).insertAfter(sidebar); } // If the tester is below the div, make sure the class "bottom" is set. if (testPosition(tester)) { sidebar.addClass("bottom"); console.log("Add class"); } else { sidebar.removeClass("bottom"); console.log("remove class"); } } function testPosition(sidebar) { console.log(sidebar.offset().top + " + " + sidebar.outerHeight() +" >= " + sidebar.parent().offset().top + " + " + sidebar.parent().outerHeight()); if (sidebar.offset().top + sidebar.outerHeight() >= sidebar.parent().offset().top + sidebar.parent().outerHeight()) return true; return false; } 

HTML

 
La la links
Pooper scooper!
De body

有关正在进行的操作的直观说明,请在向下滚动时查看http://jsfiddle.net/M5sMx/38/ ,您将看到“tester”对象正在执行的操作。