简体   繁体   English

jQuery调整大小或滚动功能不起作用?

[英]Jquery resize or scroll function not working?

function navbarBackground() {
    if ($(window).width() > 639) {
        $(document).scroll(function () {
            if ($(window).scrollTop() > 60) {
                $('.navbar').addClass('back', 250);
            } else {
                $('.navbar').removeClass('back', 250);
            }
        });
    } else {
        $('.navbar').addClass('back', 250);
    }
}

$(window).resize(function() {
    navbarBackground();
});

$(document).ready(function() {
    navbarBackground();
}

I need when user scrolls over 60px to add class and remove it if it's scrolled less than 60px only if screen width is more than 639px, and when it shrinks it adds class even if it's not scrolled, and also to do that on resize and window ready. 我需要当用户滚动超过60px时添加类,并且仅当屏幕宽度大于639px时才将其滚动到小于60px时,将其删除;缩小时,即使它没有滚动,它也会添加类,并在调整大小和窗口时进行添加准备。 The problem is that my scroll function applies on less than 639px, so when i scroll down and scroll back to top it removes the class but it shouldn't (on small screen). 问题是我的滚动功能适用于小于639像素,因此当我向下滚动并向后滚动到顶部时,它将删除该类,但不应删除(在小屏幕上)。 What is the problem? 问题是什么?

Your logic for the given requirements is flawed as you attach the scroll handler once for every pixel the window is resized. 当您为窗口调整大小的每个像素附加一次scroll处理程序时,满足给定要求的逻辑存在缺陷。 You also only check the window width within the navbarBackground() function, never when then window size is changed. 您也只检查navbarBackground()函数中的窗口宽度, navbarBackground()检查窗口大小何时更改。

Try this simplified version: 尝试以下简化版本:

function handleHeaderState() {
    var $win = $(this);
    $('.navbar').toggleClass('back', $win.scrollTop() > 60 && $win.width() > 639);
}

$(window).on({
    scroll: handleHeaderState, // on scroll
    resize: handleHeaderState // on resize
});

handleHeaderState(); // on load

Example fiddle 小提琴的例子

function navbarBackground() {
  if ($(window).width() > 639) {
    $('.navbar').removeClass('back', 250);
    $(document).scroll(function () {
      if ($(window).scrollTop() > 60) {
        $('.navbar').addClass('back', 250);
      }
      else {
        $('.navbar').removeClass('back', 250);
      }
    });
  }
  else {
    $(document).unbind('scroll');
    $('.navbar').addClass('back', 250);
  }
}

$(window).resize(function() {
    navbarBackground();
});


$(document).ready(function() {
  navbarBackground();
}

i solved it this way, thanx! 我是这样解决的,thanx!

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

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