【问题标题】:Dynamically readjusting image depending on the height根据高度动态调整图像
【发布时间】:2020-11-23 16:03:24
【问题描述】:

我正在尝试重做that example 作为练习。

当我点击上面或下面的文本时,我试图让图像 div 动态重新调整。

所以我画了一个草图来试试。但是我被卡住了,因为当 div expanded 打开时我不知道如何计算剩余空间,因此图像适合该空间。

jQuery(document).ready(function($)
{
  $("#ex").click(function()
  {
    $("#expanded").slideToggle(200)
      if ($("#ex").text() == "infos")
      {         
         $("#ex").html("close")
         $("#fit-picture").css("height", "20px");
      }
      else 
      { 
         $("#ex").text("infos")
         $("#fit-picture").css("height", "100vh");
      }
  });  
});
body{margin:0}

.container{ 
    height: 100%;
  min-height: 100%;}

#expanded{
    margin-top: 0px;  
    background: gray;
    width: 50vw; height: 50vh;
}



#ex {
    display: block;
    width: 50vw;
    background-color:darkgrey;
    text-decoration:none;
}

#ex:hover {
  background:black;
}

.container{
height:100vh;
}

#fit-picture{
  width: auto;
  height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="container">
  <div class="expand">
  <a href="#" id="ex">infos</a>
</div> 
<div id="expanded" style="display: none;">the image is supposed to be reduced proportionally to fit the remaining space of the screen.
</div>
<img id="fit-picture"
     src="https://www.wanimo.com/veterinaire/wp-content/uploads/2018/11/chat-jaloux-e1574672723199@2x.jpg">
</div>

【问题讨论】:

    标签: html jquery css responsive-design


    【解决方案1】:

    因此,它并不是真正的自适应,您必须在之前定义所有高度,但这里有一个解决方案:

    jQuery(document).ready(function($)
    {
      
      $("#ex").click(function()
      {
        
        $("#expanded").slideToggle(200)
    
          if ($("#ex").text() == "infos")
          {         
            $("#ex").html("close")
    
            $("#fit-picture").animate({height:"45vh"}, 200) ;
    
    
           
            
          }
          else 
          { 
            $("#ex").text("infos")
            $("#fit-picture").animate({height:"95vh"}, 200);
          }
        
      });  
      
    });
    

    【讨论】:

      【解决方案2】:

      在 HTML 中,将您的图片标签替换为以下内容:

      <img id="fit-picture" src="https://www.wanimo.com/veterinaire/wp-content/uploads/2018/11/chat-jaloux-e1574672723199@2x.jpg" class="center">
      

      在 CSS 中,粘贴

      .center {
        display: block;
        margin-left: auto;
        margin-right: auto;
        width: 50%;
      }
      

      您应该以 % 而不是 px 来提及高度和宽度。这将有助于每次调整图像大小以调整窗口大小。这将是完成工作的最简单方法。

      【讨论】:

      • 很抱歉,我不应该说清楚。你检查过我在我的问题中提出的例子吗?我要做的是根据元素的总高度重新调整图像高度,具体取决于它们是打开还是关闭。
      • @pual - 如果这不是您想要的,我很抱歉。如果您将高度和宽度定义为 % 而不是 px,这应该是最简单的方法,因为它将采用定义的百分比量,因此,当您调整窗口大小时,高度和宽度会发生变化。
      猜你喜欢
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 2018-05-08
      • 1970-01-01
      相关资源
      最近更新 更多