使用JavaScript确定屏幕尺寸媒体查询



是否有一种简单的方法来确定当前使用JavaScript的断点"模式"?

例如,我正在使用SASS根据仅$中小型,仅中型等的变量来设置视图。但是,如果用户已经调整了浏览器大小,并且正在使用$仅大的断点,我希望能够在JavaScript中查询此问题。因此,类似以下内容:

if ($small) {
    // do something
} else {
    // do something different
}

var debouncer = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; }
    if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();
function breakpointCheck() {
  var $r = $(".responsiveChecker");
  
  if ($r.css("font-weight") === "500" ) {
    return 5;
  } else if ($r.css("font-weight") === "400" ) {
    return 4;
  } else if ($r.css("font-weight") === "300" ) {
    return 3;
  } else if ($r.css("font-weight") === "200" ) {
    return 2;
  } else if ($r.css("font-weight") === "100" ) {
    return 1;
  }
}
try { console.log("Breakpoint: " + breakpointCheck()); } catch(err) {}
$(window).on("resize", function() {
  debouncer(function() {
    console.log("Breakpoint: " + breakpointCheck());
  }, 500);
});
.responsiveChecker {
    font-weight: 500;
}
@media (max-width: 1600px) {
    .responsiveChecker {
        font-weight: 400;
    }
}
@media (max-width: 1120px) {
    .responsiveChecker {
        font-weight: 300
    }
}
@media (max-width: 767px) {
    .responsiveChecker {
        font-weight: 200
    }
}
@media (max-width: 374px) {
    .responsiveChecker {
        font-weight: 100
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="responsiveChecker"></div>

我已经为您想实现的目标整理了一个编码器:https://codepen.io/mayhembliz/pen/mogmpw

最新更新