0

The value of !$catalog.hasClass('catalog-fixed') in line 6 is always true

$(window).scroll(function(){
      var $catalog = $(".catalog-brief");
      var sideTop = $catalog.offset().top;
      if (sideTop < 1000){
           // always true
           if (!$catalog.hasClass('catalog-fixed')) $catalog.addClass("catalog-fixed");
      } else {
           if ($catalog.hasClass('catalog-fixed')) $catalog.removeClass("catalog-fixed");
     }
})

But this works fine

var $catalog = $(".catalog-brief");
var sideTop = $catalog.offset().top;
$(window).scroll(function(){
      if (sideTop < 1000){
           if (!$catalog.hasClass('catalog-fixed')) $catalog.addClass("catalog-fixed");
      } else {
           if ($catalog.hasClass('catalog-fixed')) $catalog.removeClass("catalog-fixed");
     }
})

Did I make any mistakes?

刘晚林
  • 65
  • 4
  • 6
    There's nothing wrong with `hasClass`, but it seems like you really should be using **`toggleClass`** – adeneo Apr 21 '15 at 01:01

2 Answers2

1

Try to use window.scrollY instead of the current sideTop. Or $(window).scrollTop() if you want to use Jquery.

$(window).scroll(function(){
      var $catalog = $(".catalog-brief");

      // if ($(window).scrollTop() < 1000) {
      if (window.scrollY < 1000) {
           if (!$catalog.hasClass('catalog-fixed')) $catalog.addClass("catalog-fixed");

      } else {
           if ($catalog.hasClass('catalog-fixed')) $catalog.removeClass("catalog-fixed");
     }
});
0

Can you try this:

  var $catalog = $(".catalog-brief");
  var sideTop = $catalog.offset().top;
  $(window).scroll(function(){
      (sideTop < 1000) &&  ($catalog.toggleClass("catalog-fixed"))
  })

See: https://stackoverflow.com/a/11069385/1845408

Community
  • 1
  • 1
renakre
  • 8,001
  • 5
  • 46
  • 99