检测附加元素何时返回其原始位置

Detect when an affixed element has returned to its original position

如何检测 Bootstrap 附加元素何时返回到其起始位置并且不再附加?

更新的答案:显然,Affix 插件带有事件来处理这类事情。来自 W3C Schools 的示例:

$(document).ready(function(){
    $('.nav').affix({offset: {top: 150} }); 
    $('.nav').on('affix-top.bs.affix', function(){
        alert('The navigation menu is about to return to its original top position - The .affix class is about to be replaced with .affix-top');
    });
});

还有其他事件,例如 affix-bottom.bs.affix 当元素 returns 到达最底部位置时触发。

原回答: 来自W3C Schools

The affix plugin toggles between three classes: .affix, .affix-top, and .affix-bottom. Each class represents a particular state. You must add CSS properties to handle the actual positions, with the exception of position:fixed on the .affix class.

所以我想你可以这样做:

$(window).scroll(function() {
    if($("#element").css("position") === "fixed") {
         //It is fixed.
    }
    else {
        //It is not fixed.
    }    
});

如果你只想在状态改变时执行代码,那么保留一个记住状态的全局变量。在滚动事件中,检查当前状态是否与全局变量匹配。如果不是,则状态已更改。