繁体   English   中英

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

[英]Determine screen-size media query using Javascript

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

例如,我使用SASS根据$ small-only,$ medium-only等变量设置视图。 但是,如果用户调整了浏览器的大小,并且使用了$ small-only断点,我希望能够使用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> 

我为我想您要实现的目标编写了一个Codepen: https ://codepen.io/MayhemBliz/pen/MOGMpW

暂无
暂无

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

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