【问题标题】:I need to change the img depending on the windows width我需要根据窗口宽度更改 img
【发布时间】:2016-04-01 05:13:23
【问题描述】:

我想要的是在窗口较小时更改图像。

例如,当窗口 900时,它将是一个不同的图像。

我不知道如何使用不同的窗口大小来做到这一点?

【问题讨论】:

    标签: jquery html css image responsive-design


    【解决方案1】:

    您可以像这样使用 css 媒体查询:

    @media (max-width:900px) {
       #targetElement { background-image: url('...') }
    }
    
    @media (min-width:901px) {
       #targetElement { background-image: url('...') }
    }
    

    @media

    【讨论】:

      【解决方案2】:

      你可以试试这个jquery:

      var width = $(window).width(); 
      if (width >= 900) {
          //do something
      } else {
          //do something else
      }
      

      【讨论】:

      • 这行得通,但只有一次。如果将其包装在事件侦听器中,则每次用户调整页面大小时都会发生这种情况。
      • 你可以将上面的代码包装在一个函数中,然后你可以使用 window.addEventListener("resize", myFunction);
      • 也可以使用 $( window ).resize(function() { //call function here })
      【解决方案3】:

      您可以使用媒体查询,并将 display:none 设置为所需的宽度。

      <img src="http://*" class="image1"></img>
      
      @media (max-width:900px) { .image1 { display:none } }
      

      【讨论】:

      • 聪明的方法。您可以在页面上有 2 张图片,然后根据宽度使用媒体查询仅显示一张。一个缺点是许多浏览器会在页面加载时同时加载这两个图像,这会变慢。
      【解决方案4】:

      你可以通过 CSS 来实现,如下所示

       @media screen and (max-width: 900px) {
       #id{/*Your CSS here */} }
      

      【讨论】:

        【解决方案5】:

        您还将使用 jquery 来执行此操作:-

        var width = $(window).width();
        
        if(width > 900){
             $('#img-id').attr('src','path/to/image');
        }else{
            $('#img-id').attr('src','path/to/image');
        }
        

        【讨论】:

          【解决方案6】:

          您需要的是一个事件监听器。每次调整窗口大小时,让 jQuery 检查宽度。如果它高于/低于某个阈值,请调整图像。像这样的:

          $(window).resize(function() {
              var width = $(window).width();
              $("#width-num").html(width);
          
              if(width > 500) {
                  $("#img-change").attr("src", img2);
              } else {
                  $("#img-change").attr("src", img1);
              }   
          });
          

          See fiddle for example

          【讨论】:

            【解决方案7】:

            你可以用 jQuery 来做

            $(window).resize(function() { 
              if($(window).width() > 900){
               $('Your target div').html('<img src="Ur Image" />');
              } 
              else { 
              $('Your target div').html('<img src="Ur Different Image" />'); 
              } 
            });
            

            【讨论】:

            • 是的,但这缺少事件监听器。我怀疑每次用户调整窗口大小时 OP 都想运行它。
            猜你喜欢
            • 2012-04-22
            • 2017-04-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-01-25
            • 1970-01-01
            • 2015-11-30
            • 2012-09-28
            相关资源
            最近更新 更多