【问题标题】:jquery media queries changed cssjquery媒体查询改变了css
【发布时间】:2018-02-09 03:41:08
【问题描述】:

一段时间以来,我一直在尝试找出代码中的错误,但我不知道出了什么问题。有什么想法吗?

$(document).ready(function(){
        checkSize();
        $(window).resize(checkSize);
    });
    
    
    function checkSize(){
      if($(".testClass").css("float") == "none"){
          window.alert("Test");
      }
    }
.testClass{
      float: left;
    }
    
    @media(max-width: 768px){
      .testClass{
        float: none;
      }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【问题讨论】:

  • 你想做什么
  • 通过观察 css 属性是否被更改来向我的 js 添加媒体查询。
  • 媒体查询是根据屏幕宽度或高度添加样式
  • $(document).ready(function(){ console.log("Test1"); checkSize(); $(window).resize(checkSize); });函数 checkSize(){ if($(".testClass").css("float") == "none"){ console.log("Test"); } }
  • 你能描述一下应该发生什么

标签: javascript jquery html media-queries responsive


【解决方案1】:

使用$(window).width(),您可以获得视口宽度并对其进行任何验证。

$(document).ready(function() {
  console.log('Window width: '+ $(window).width());
  checkSize();
});

function checkSize() {
  if($(window).width() < 768) {
    console.log("Run code...");
  }
}
.testClass {
  float: left;
}

@media(max-width: 768px) {
  .testClass {
    float: none;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testClass"></div>

【讨论】:

  • @STAT1C 我希望我的回答能解决您的问题。如果你还没有接受答案,你能帮我解释为什么会这样。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-08-14
  • 1970-01-01
  • 2022-01-25
  • 2013-12-22
  • 2021-08-23
  • 2012-02-15
  • 2013-03-05
相关资源
最近更新 更多