【问题标题】:Changing css with Jquery in different screen size [duplicate]在不同的屏幕尺寸下使用 Jquery 更改 css [重复]
【发布时间】:2021-01-19 12:05:14
【问题描述】:

当我删除 if() {} 时,此代码可以正常工作,但我希望 css 样式仅适用于特定的窗口宽度。当我添加 if 语句时,它不再读取 CSS 样式。知道为什么吗?

$(document).ready(function() {
   $(".icon").mousemove(function() {
      $(this).hide();
      $(".second").show(2000);
      if (windows.innerWidth > 768) {
        $(".second").css({
          "display": "grid",
          "grid-template": "200px / 200px 200px"
        });
      }
   });    
});


I also tried this and still not working:

$(document).ready(function(){
    $(".icon").mousemove(function() {

        $(this).hide();
        $(".second").show(2000);
        if ($(window).width() > 768){
          $(".second").css({
            "display": "grid",
            "grid-template": "200px / 200px 200px"
             });
        }

        else {
          $(".second").css({
            "display": "grid",
            "grid-template": "100px / 100px 100px"
             });
        }

        });
    
    });

【问题讨论】:

标签: javascript jquery css


【解决方案1】:

在您的 css 文件中,您可以使用这样的媒体查询。

@media only screen and (max-width: 768px) {
    .second{
        display: grid;
        grid-template: 200px / 200px 200px;
    }
}

Learn more about media queries

【讨论】:

  • 谢谢,但我希望用 Javascript 实现
  • 能否请您将问题中的代码块设为 sn-p 并提供不仅仅是 js。
【解决方案2】:

您可以使用 $(window).width() 函数来获取窗口宽度。

if ($(window).width() > 768) {

 // write you css here for screen size is more then 768
}else{

// write you css here for screen size is less then 768
}

【讨论】:

    【解决方案3】:

    请试试这段代码,在不同的屏幕尺寸下用 Jquery 改变 CSS

    <div id="outer-div">
        <div id="inner-div">
        <H2>Switch CSS On Window Resize</H2>
        </div>
        <div id="menu-div">
        <H2>Tags</H2>
        <a class="demo-tag">Fluid</a>
        <a class="demo-tag">Stylesheet</a>
        <a class="demo-tag">Resize</a>
        <a class="demo-tag">Demo</a>
        <a class="demo-tag">Examples</a>
        </div>
    </div>
    

    Javascript 和 Jquery:

    <script>
        function switchCSS(windowsize) {
          if (windowsize > 800) {
            $("#switchable").attr("href", "web.css");
          } else {
             $("#switchable").attr("href", "mobile.css"); 
          }
        }
    
        $(document).ready(function() {
          switchCSS($(this).width());
          
          $(window).resize(function() {
            switchCSS($(this).width());
          });
        });
    </script>
    

    我希望这段代码对你有用。

    谢谢。

    【讨论】:

      猜你喜欢
      • 2012-02-29
      • 2018-01-07
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多