Javascript 试图在页面顶部获得固定菜单,但返回错误的Y位置

Javascript 试图在页面顶部获得固定菜单,但返回错误的Y位置,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试创建一个程序页面,该页面包含可以通过单击按钮展开的列。当你到达程序的某一点时,一个菜单将出现并停留在页面的顶部。但是,当您展开其中一列时,如果Y位置没有正确返回,则会出现问题。这会使菜单过早跳转到页面顶部 我的Jquery知识有限,所以我希望有人能帮助我。我试着寻找答案,但不幸的是还没有结果 HTML: JQuery: $(document).ready(function () { $('#column1').click(function() { if ($('div#col

我正在尝试创建一个程序页面,该页面包含可以通过单击按钮展开的列。当你到达程序的某一点时,一个菜单将出现并停留在页面的顶部。但是,当您展开其中一列时,如果Y位置没有正确返回,则会出现问题。这会使菜单过早跳转到页面顶部

我的Jquery知识有限,所以我希望有人能帮助我。我试着寻找答案,但不幸的是还没有结果

HTML:

JQuery:

$(document).ready(function () {

$('#column1').click(function() {
    if ($('div#column1').height() > 251) {
        ($('div#column1').animate({height: '250px', navigation: true}))
    } else {
        ($('div#column1').animate({height: '500px', navigation: true}));
    }
});


    var top = $('#fixed-row').offset().top;

    $(window).scroll(function () {

    //Y position of scroll
    var y = $(window).scrollTop();

    //Whether below form
    if (y >= top) {

    //If so, add class fixed
    $('#fixed-row').addClass('fixed');
    }else {

    //Otherwise remove class fixed
    $('#fixed-row').removeClass('fixed');
    }

});

});
非常感谢您提前

基本上,您可以在动画之前计算top值,之后不进行更新。动画完成后,需要对其进行更新

试着这样做:

$(document).ready(function () {

    var top = $('#fixed-row').offset().top;

$('#column1').click(function() {
    if ($('div#column1').height() > 251) {
        ($('div#column1').animate({height: '250px', navigation: true},function() { top = $('#fixed-row').offset().top; }));
    } else {
        ($('div#column1').animate({height: '500px', navigation: true},function() { top = $('#fixed-row').offset().top; }));
    }
});

只需按以下方式进行更改即可

$(window).scroll(function () {
    var top = $('#column1').height();
//Y position of scroll
var y = $(window).scrollTop();

//Whether below form
if (y >= top) {

//If so, add class fixed
$('#fixed-row').addClass('fixed');
}else {

//Otherwise remove class fixed
$('#fixed-row').removeClass('fixed');
}   });

调用函数后,将var top更新为新的offset.top。工作正常!非常感谢你!谢谢你的意见!我发现上面的修复更容易实现,但非常感谢!好的,很高兴你找到了解决办法。但是,请记住,上面的解决方案似乎只在元素从页面开始时才起作用。如果与上边框有偏移,则会失败。如果它在您的情况下有效,那么如果您不关心性能问题,它确实是更好的解决方案。看起来您是对的。。。更改了最佳答案标签。。再次感谢:
$(document).ready(function () {

    var top = $('#fixed-row').offset().top;

$('#column1').click(function() {
    if ($('div#column1').height() > 251) {
        ($('div#column1').animate({height: '250px', navigation: true},function() { top = $('#fixed-row').offset().top; }));
    } else {
        ($('div#column1').animate({height: '500px', navigation: true},function() { top = $('#fixed-row').offset().top; }));
    }
});
$(window).scroll(function () {
    var top = $('#column1').height();
//Y position of scroll
var y = $(window).scrollTop();

//Whether below form
if (y >= top) {

//If so, add class fixed
$('#fixed-row').addClass('fixed');
}else {

//Otherwise remove class fixed
$('#fixed-row').removeClass('fixed');
}   });