【问题标题】:Jquery and media queriesJquery 和媒体查询
【发布时间】:2019-12-28 09:45:24
【问题描述】:

简单的问题 - 是否可以将 jquery 与媒体查询一起使用,以便 jquery 仅发生在特定屏幕尺寸以下。

我有一个在桌面上使用悬停的导航,但我需要在移动设备上使用点击。

我想在移动设备上控制一些其他操作,例如按钮上的 preventDefault() 操作

【问题讨论】:

标签: jquery media-queries


【解决方案1】:

您可以在窗口的调整大小功能中做到这一点:

$(window).on('resize', function (e) {
    var width = $(window).width();

    if (width > 1024)
        // Codes
});

【讨论】:

    【解决方案2】:

    调整窗口大小不是很好。

    最好的方法是使用 matchmedia

    var mql = window.matchMedia("screen and (min-width: 800px)")
    if (mql.matches){ // if media query matches
     alert("Window is 800px or wider")
    }
    else{
     // do something else
    }
    

    附:确保你下载了 Typescript

    【讨论】:

      【解决方案3】:

      @Mohamad Shiralizadeh

      这看起来不错。然而,它仅在窗口调整大小时触发。当您第一次加载页面时,它不会触发。所以根据你的例子:

      jQuery(document).ready(function ($) {
      // do things when the document is ready
      contentChanger();
      // do things when the widow resizes 
      $(window).resize(function () {
          contentChanger();
      });
      
      
      // change content based on viewport
      function contentChanger() {
          // viewport is 320 pixels or smaller
          if ($(window).width() <= 320) {
              // do things here
          }
      
          // viewport is 375 pixels or smaller but bigger than 320 pixels
          if ($(window).width() <= 375 && $(window).width() > 320) {
              // do things here
          }
      };
      

      });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-22
        • 2013-08-10
        • 2012-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多