【问题标题】:jQuery .load and .resize doesn't work properlyjQuery .load 和 .resize 不能正常工作
【发布时间】:2017-10-14 04:31:15
【问题描述】:

我有一个带有滚动功能的加载和调整大小功能,它应该在 992 像素以上的屏幕上的窗口滚动上显示一个固定的标题。

在 992px 以下的屏幕上,我使用静态定位的相同标题,问题是 .load 和 .resize 功能无法正常工作。

我希望函数像媒体查询一样保持一致,我不知道这是否可能,如果有人知道该怎么做,我将不胜感激。

JSFiddle

$(window).on('load resize', function() {
      if($(window).width() > 992) {
        function header_fixed_scroll() {                          
          if ($(this).scrollTop() > 200) {
            $('.header-fixed').show();
          } else {
            $('.header-fixed').hide();
          }
        }
        $(document).ready( function () {
          header_fixed_scroll();
        $(window).on('scroll', header_fixed_scroll);
    });
   };
  });
body {
  height:1500px;
}

.header-fixed {
  position:fixed;
  top:0;
  width:100%;
  height:70px;
  background:red;
  display:none;
}

@media screen and (max-width:991px) {
  .header-fixed{
    position:static;
    display:block;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div class="header-fixed"></div>
</body>

【问题讨论】:

  • 为什么你使用 js 来做这个?你只能用css来做。位置:固定;
  • 我不希望它是位置:固定在 992px 以下的屏幕上
  • 所以使用媒体查询:w3schools.com/css/css3_mediaqueries_ex.asp BTW,试试使用 position:sticky
  • 但我无法使用媒体查询使滚动功能不显示
  • 检查小提琴jsfiddle.net/3fvudr2h/13

标签: javascript jquery html css scroll


【解决方案1】:

试试这个代码修复:

function header_fixed_scroll() {
  if ($(this).scrollTop() > 200) {
    $('.header-fixed').show();
  } else {
    $('.header-fixed').hide();
  }
}
$(document).ready(function() {
  $(window).on('load resize scroll', function() {
    if ($(window).width() > 992) {
      header_fixed_scroll();
    };
  });
});
body {
  height: 1500px;
}

.header-fixed {
  position: fixed;
  top: 0;
  width: 100%;
  height: 70px;
  background: red;
  display: none;
}

@media screen and (max-width:991px) {
  .header-fixed {
    position: static;
    display: block;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="header-fixed"></div>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2011-04-16
    • 2016-07-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多