固定div滚动

时间:2016-05-05 09:08:23

标签: javascript jquery html css

我正在尝试创建一个div,它只会在滚动时获得一个类,当scroll的值为210时。我有下一个代码:

$(document).ready(function() {
    var pageWidth = $(window).width();

    if(pageWidth > 700){
        var contentLeft = $('#content-left');
        var height = 210;

        $(window).scroll(function () {
            if ($(window).scrollTop() < height) {
                contentLeft.attr('class', 'content-left');
            } else {
                contentLeft.attr('class', 'content-left leftContentFixed');
            }
        });
    }
});

我尝试仅在桌面上应用此功能。 因此,如果它在智能手机或平板电脑上,我不需要类leftContentFixed。

如果我尝试这样的话:

$(document).ready(function() {
    var pageWidth = $(window).width();

    if(pageWidth > 700){
        alert("Bigger than 700");
    }else{
        alert("Smaller than 700");
    }
});

比它完美,但是我的代码无效。尽管屏幕小于700,但仍添加了leftContentFixed类。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您需要检查resize事件的屏幕大小,并在用户滚动页面时检查其值。您可以创建mobile变量并使其true/false取决于屏幕大小,然后在scroll回调检查其值并选择正确的类。

&#13;
&#13;
$(document).ready(function() {
  var pageWidth = $(window).width(),
    height = 210,
    contentLeft = $('.content-left'),
    mobile = false;

  $(window).on('load resize', function() {
    pageWidth = $(this).width();
    // Save mobile status
    if (pageWidth > 700) {
      mobile = false;
    } else {
      mobile = true
    }
  })

  $(window).on('scroll', function() {
    if ($(window).scrollTop() > height) {
      // Set default class
      var _class = 'content-left leftContentFixed';
      // If mobile then modify class
      if (mobile) {
        _class = 'content-left';
      }
      contentLeft.attr('class', _class);
    } else {
      var _class = 'content-left';
      contentLeft.attr('class', _class);
    }
  });

});
&#13;
html {
  height: 2000px
}

.content-left {
  background: gold;
  width: 50px;
  height: 100px;
}

.content-left.leftContentFixed {
  position: fixed;
  top: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-left"></div>
&#13;
&#13;
&#13;