【问题标题】:media query with jquery使用 jquery 进行媒体查询
【发布时间】:2022-02-07 03:39:43
【问题描述】:

我想检查是否可以添加媒体查询。

例如, 如果窗口大小在 700px 到 1000px 之间,则更改超链接的某些文本(类名:“samplebutton”从“ABC”到“DEF”。

我得到了这样的东西……但它抛出了一个错误……不知道出了什么问题……

<script>
    jQuery(document).ready(function() {
        if($(window.width()) >= 700) {        
        jQuery('a.samplebutton').text("DEF");   
    }   
});

</script>

我不精通编程,但如果你能展示一些示例代码行,我将能够从那里拿走它……你能帮忙吗?

谢谢

【问题讨论】:

    标签: jquery media-queries


    【解决方案1】:

    如果你想在屏幕大小改变时改变任何元素的内容,你需要使用事件监听器。

    jQuery(document).ready(function() {
      /* Prints the current mode and screen width. */
      function log(width, mode) {
        console.clear();
        console.log(`Mode: ${mode} Width: ${width}px`);
      }
    
      /* This method is called when the resize event is triggered. */
      function update(object) {
        let width = object.width();
        let mode;
        
        $('#result').text(`${width}px`);
        
        /* Dekstop Mode */
        if(width >= 1024) {
          mode = 'Desktop';
          $('#engine').text('Google');
        }
        /* Tablet Mode */
        else if(width < 1024 && width > 768) {
          mode = 'Tablet';
          $('#engine').text('Google');
        }
        /* Mobile Mode */
        else if(width <= 768) {
          $('#engine').text('Yahoo');
          mode = 'Mobile';
        }
        
        log(width, mode);
      }
    
      /* The resize event fires when the page width changes. */
      $(window).on('resize', function(){        
        update($(this));
      }); 
      
      update($(this));
    });
    p {
      display: inline;
    }
    .samplebutton {
      background-color: #4CAF50;
      color: white;
      padding: 10px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <span>Page Width: </span>
    <p id="result"></p><hr>
    
    <a id="engine" class="samplebutton" href="https://www.google.com">Google</a>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      • 2014-01-29
      相关资源
      最近更新 更多