在窗口调整大小上添加类

时间:2020-05-15 20:37:22

标签: jquery resize toggle

如果windowsize超过299,我将切换类,并且仅在窗口较小时才添加类。它现在以某种方式可以工作,我不知道为什么。

感谢您的帮助!

问候 本

编码窗口大小的代码:

$(document).ready(function () {
    var eventFired = 0;
  function windowSize() {
    windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
    windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
  } 
  windowSize();

如果声明:

  $(window).resize(function() {
    windowSize();
    //console.log('width is :', windowWidth, 'Height is :', windowHeight);
    if (windowWidth > 299) {
    $('#topBarToggler, #toggleheading').on('click', function () {
        $('#sidebar').toggleClass('active');
        event.stopPropagation();
    });
    $("#content").click(function () {
        $('#topBarToggler, .toggleheading').prop('checked', true);
        $('#sidebar').removeClass('active');
    });
} else {
    $('#topBarToggler, #toggleheading').on('click', function () {
        $('#sidebar').addClass('active');
}

}
});

1 个答案:

答案 0 :(得分:0)

请考虑以下代码。

function windowSize() {
  return {
    height: window.innerHeight ? window.innerHeight : $(window).height(),
    width: window.innerWidth ? window.innerWidth : $(window).width()
  };
}

然后您可以像这样使用它:

$(window).resize(function() {
  var wSize = windowSize();
  if (wSize.width > 299) {
    $('#topBarToggler, #toggleheading').on('click', function (event) {
      $('#sidebar').toggleClass('active');
      event.stopPropagation();
    });
    $("#content").click(function () {
      $('#topBarToggler, #toggleheading').prop('checked', true);
      $('#sidebar').removeClass('active');
    });
  } else {
    $('#topBarToggler, #toggleheading').on('click', function () {
      $('#sidebar').addClass('active');
    });
  }
});

如您所见,创建了一个对象并返回了两个索引:widthheight。您可以运行此功能并收集所需的详细信息。

相关问题