javascript - 屏幕尺寸大于1024px才执行JS?

标签 javascript jquery

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

关于javascript - 屏幕尺寸大于1024px才执行JS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31429055/

相关文章:

javascript - ForEach 循环是否允许使用 break 和 continue?

javascript - 服务器和客户端验证器 - 库

javascript - 为 Rails 设置 JavaScript 格式

javascript - 如何收集选中的单选按钮并放入数组中然后发布到 Controller

javascript - 为什么modal弹出按空格键会按?我该如何预防?

php - jquery 序列化方法的多种形式不起作用

javascript - jquery 检查变量值

javascript - 两个日期之间的天数 kendo DateTimePicker

javascript - 为什么自定义验证器在 jQuery 的 document.ready 中不起作用

javascript - 尝试从 jQuery 提交异步调用时在有效 URL 上获取 404