jquery - 调整窗口大小时多次调用函数 [JQuery]

标签 jquery html css

这是我正在尝试做的事情:

-当窗口的宽度小于700px,用户点击底部的灰色栏,红色菜单会向上滑动并停留在那里。

-当窗口的宽度大于700px时,用户点击灰色条时不会发生任何事情。

我已将 resize() 事件绑定(bind)到浏览器窗口,因此如果用户在页面加载后调整窗口大小,将检测到更改。

这是我的代码笔: http://codepen.io/Chiz/pen/xwrpWG (在您阅读下文之前,请勿点击!)

以下是产生奇怪问题的方法:

1) 在单击上面的 Codepen 链接之前,将窗口大小调整到 700px 以下,然后单击上面我的 codepen(如果不确定 700px 有多宽,请将其设置得非常小)

2) 单击底部的灰色条。红色矩形应该向上滑动并停止。 再次点击。红色矩形向后滑动。反复点击,红色矩形每次上下滑动。这是正确的行为。

3) 现在,无需重新加载或刷新 codepen 即可调整浏览器宽度。 您可以使其变宽或变窄,只要调整窗口大小都无所谓。 再次单击灰色条。错误出现。红色矩形向上向下滑动 MULTIPLE 次!

有时,调整大小的次数越多,滑动的次数就越多! :-O

我该如何解决这个问题?

//bind click event to the gray bar on page's first load
showMenuIfWidthSmallerThanSevenHundred();

//detect window resizes
$(window).resize(function() {
  showMenuIfWidthSmallerThanSevenHundred();
});


function showMenuIfWidthSmallerThanSevenHundred() {
  if ($(window).innerWidth() <= 700) {
    $("div").on("click", function() {
      /* make menu fill the entire screen that is
      not occupied by the gray bar */
      var nMenuHeight = $(window).height() - $(this).height();

      $(".menu").height(nMenuHeight);

      /* position the menu so that the bottom of the menu
      touches the top of the gray bar */
      $(".menu").css("bottom", $(this).height());

      //make menu slide upwards / downwards
      $(".menu").slideToggle();
    });
  }
}
div {
  width: 100%;
  height: 53px;
  background-color: gray;
  position: absolute;
  bottom: 0;
}
.menu {
  width: 100%;
  height: 100px;
  background-color: #F08080;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div></div>

<div class="menu"></div>

最佳答案

您可以进行去抖动以减少触发事件的次数。我推荐 Paul Irish 的 smartresizer,它使用 debouces 来达到这个目的。

http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/

正如教程所说,您可以使用这个简单的监听器:

 $(window).smartresize(function(){
    // code that takes it easy...
 });

您可以消除大量触发事件的抖动,例如调整大小、滚动等。

关于jquery - 调整窗口大小时多次调用函数 [JQuery],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33035149/

相关文章:

javascript - 可以包含 javascript 的 HTML 属性

css - 在 asp.net .master 页面中使用 CSS 居中 Label 元素的正确方法是什么

jquery - 3 列字段 Bootstrap

javascript - 使用 AJAX,并检索就绪状态

javascript - 如何更改 vimeo 默认皮肤

html - "Check"单击并拖动多个复选框?

html - 样式化上传按钮

html - 为什么这个元素在表格外面?

php - 自定义帖子类型显示缩略图 - WordPress

jquery - 换头像功能