通过CSS为jQuery存储媒体查询结果

问题描述 投票:0回答:2

有一些媒体查询无法在JavaScript中完成,所以我一直将它们存储为CSS中的虚拟属性以使用jQuery进行检测:

CSS

#mobile-check{
  display:none;
  z-index:1;
}
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 812px) 
  and (-webkit-min-device-pixel-ratio: 3) {
    #mobile-check {
        z-index:2;
    }
}

HTML

<html>
<body>
    <div id="mobile-check">
        <!-- checks device-width, leave empty -->
    </div>
    <div id="content">
        <!-- content -->
    </div>
</body>
</html>

JS

var mobile = false;
var check = $("#mobile-check").css("z-index");
if (check==2) { mobile = true; }
if(mobile){ [...] }

我只是想知道这是否被认为是不好的做法,或者是否已经建立了这样做的方法。

jquery css
2个回答
1
投票

也可以使用window.matchMedia,如果需要,你也可以在resize事件中使用它

if (window.matchMedia("(min-width: 400px)").matches) {
  /* the viewport is at least 400 pixels wide */
} else {
  /* the viewport is less than 400 pixels wide */
}

0
投票
$(document).ready(function() {

   function responsiveRule(){
     if($(window).width < 400) {

     }
   }
   $(window).resize(function() {
     responsiveRule();
   });
});

而不是使用CSS来检查它是否是移动屏幕;可以使用window.width()。

© www.soinside.com 2019 - 2024. All rights reserved.