我有一个侧边栏,该边栏变为position:在div的底部可见时已修复(此tutorial之后)。我的问题是,如果屏幕尺寸大于或等于1025px,我只需要JS才能工作。

我知道我需要一些与if($(window).width() > 1025)相似的东西,但是我无法弄清楚需要在哪里。我对JS不太满意,因此不胜感激。

Demo

JS

$(function () {

if ($('.leftsidebar').offset()!=null) {

    var top = $('.leftsidebar').offset().top - parseFloat($('.leftsidebar').css('margin-top').replace(/auto/, 0));
    var height = $('.leftsidebar').height();
    var winHeight = $(window).height();
    var footerTop = $('#footer').offset().top - parseFloat($('#footer').css('margin-top').replace(/auto/, 0));
    var gap = 100;

    $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y+winHeight >= top+ height+gap && y+winHeight<=footerTop) {

    // if so, ad the fixed class
    $('.leftsidebar').addClass('leftsidebarfixed').css('top',winHeight-height-gap +'px');
    }
    else if (y+winHeight>footerTop) {

    // if so, add the fixed class
    $('.leftsidebar').addClass('leftsidebarfixed').css('top',footerTop-height-y-gap+'px');
    }
    else
    {
    // otherwise remove it
  $('.leftsidebar').removeClass('leftsidebarfixed').css('top','315px');
    }
  });
 }
}

最佳答案

这应该工作:

var flag = false;
// This will keep on checking for window size while you are scrolling.
$(window).on("scroll", function() {
    if (flag){
        // Do whatever you want here
        alert("hey");
    }
});

$(window).on("resize", function() {
    if ($(window).width() >= 1025){
        flag = true;
    } else {
        flag = false;
    }
})

07-24 14:20