How could I add a class of “bottom” to “#sidebar”

2019-03-05 05:50发布

问题:

I'm using the code below which adds a class of fixed to #sidebar once it reaches a certain height from the top of the site depending on what page it's on (i.e. home, single, page).

In a similar fashion, I would like to add a class of bottom to #sidebar once #sidebar reaches the bottom of its container (#content). If the user scrolls back up, the class of bottom should be removed and the class of fixed should be added back.

The goal is to try to get the fixed sidebar to move up with the rest of the content in its container once it reaches the bottom of it.

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

<div id="container">

  <div id="content">

    <div id="sidebar"></div>

    <div id="masonry"></div>

  </div>

</div>

回答1:

I believe this is what you are trying to do?

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

<div class="body">
    <div class="leftBar">
        La la links
        <div class="floater" id="floater">
            Pooper scooper!
        </div>
    </div>
De body
</div>

For a visual explanation of what is going on, see http://jsfiddle.net/M5sMx/38/ as you scroll down, you will see what the "tester" object is doing.