使用Javascript确定屏幕大小的媒体查询

时间:2017-11-23 11:30:46

标签: javascript css responsive-design

是否有一种简单的方法可以使用Javascript确定当前使用哪个断点“模式”?

例如,我使用SASS根据$ small-only,$ medium-only等变量设置视图。但是,如果用户已经调整了浏览器的大小并且正在使用$ small-only断点,我希望能够在Javascript中查询它。如下所示:

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

1 个答案:

答案 0 :(得分:0)

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