简体   繁体   English

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

[英]Determine screen-size media query using Javascript

Is there an easy way to determine which breakpoint "mode" is currently in place using Javascript? 有没有一种简单的方法可以使用Javascript确定当前使用的断点“模式”?

For example I am using SASS to set the view according to the $small-only, $medium-only etc. variables. 例如,我使用SASS根据$ small-only,$ medium-only等变量设置视图。 However if the user has resized the browser and the $small-only breakpoint is being used I'd like to be able to query this in Javascript. 但是,如果用户调整了浏览器的大小,并且使用了$ small-only断点,我希望能够使用Javascript查询。 So something like the following: 因此,如下所示:

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> 

I have put together a codepen for what I think you are trying to achieve: https://codepen.io/MayhemBliz/pen/MOGMpW 我为我想您要实现的目标编写了一个Codepen: https ://codepen.io/MayhemBliz/pen/MOGMpW

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM