繁体   English   中英

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

[英]Trying to get a fixed menu on top of page, but returning wrong Y position

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

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

HTML:

<body>
<div id="column1">Expand this div and scroll down to see the problem</div>
<div id="fixed-row"></div>
<div id="column2"></div>
</body>

CSS:

#column1{height:250px; width:200px; background-color:#545454; cursor:pointer; margin-bottom:5px; color:#fff;}

#column2{height:1000px; width:200px; background-color:#cecece;}

#fixed-row{height:50px; width:200px; background-color:#ff00ff; margin-bottom:5px;}

.fixed{position:fixed; top:0;}

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');
    }

});

});

我还创建了一个JSfiddle来说明问题

提前谢谢了

基本上,您要在动画之前计算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');
}   });

http://jsfiddle.net/jb36m/4/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM