【问题标题】:Keep height of auto height DIV when content gets hidden隐藏内容时保持自动高度 DIV 的高度
【发布时间】:2019-12-05 23:27:39
【问题描述】:

我有一个带有自动高度和图像的 div。当我单击以隐藏图像时,div 容器应保持在其高度。我知道我可以使用固定高度的 div 来实现这一点,但是因为有几个高度不同的 div/图像,我不能那样做。

https://jsfiddle.net/t6w3fkg8/

$(".content").click(function(){
"use strict";
$(this).hide();

});

【问题讨论】:

  • 你能分享你的代码吗...
  • 如果您对其中一个答案感到满意,请选择一个答案作为解决方案接受。这将帮助其他用户在未来找到解决问题的方法。

标签: html height


【解决方案1】:

display:none 表示该标签根本不会出现在页面上(尽管您仍然可以通过 dom 与它进行交互)。其他标签之间不会有空间分配给它。

visibility:hidden 表示与display:none 不同,标签不可见,但在页面上为其分配了空间。标记已呈现,只是在页面上看不到。

您目前可能正在使用display:none。改用visibility:hidden

编辑:我用visibility:hidden更新了你的小提琴:https://jsfiddle.net/xhmp8wj7/1/

【讨论】:

    【解决方案2】:

    当单击div 时,您可以向元素添加带有visibility: hidden 的类。示例:

    $(".content").click(function(){
        "use strict";
    	$(this).addClass("hidden");
    }); 
    .container {
     width: 300px;
     height: auto;
     background-color: #EFEFEF;
     padding: 10px;
     
    }
    
    .content {
    width: 100%;
    height: 500px;
    background-color: #AAA;
    }
    
    .content.hidden {
       visibility: hidden;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="container">
    <div class="content">
    </div>
    1234
    </div>

    【讨论】:

      【解决方案3】:
      .container 
       {
       width: 300px;
       height: 500px;
       background-color: #EFEFEF;
       padding: 10px; 
      }
      
      .content {
      width: 100%;
      height: 100%;
      background-color: #AAA
      }
      

      试试这样的...

      【讨论】:

      • .container类设置height
      • 如果您阅读了我的原始帖子,这是我无法做到的。我有几个容器,内容高度不同!
      【解决方案4】:

      试试这个。

      $(".content").click(function(){
         $(this).addClass('hide');
      });
      

      CSS

      .content.hide {
        visibility: hidden;
      }
      

      更新

      $(".content").click(function(){
          "use strict";
        var parentHeight = $(this).parent().height();
        $(this).parent().css({'height' : parentHeight+'px'});
          $(this).toggleClass("content-magnified");
      });
      

      【讨论】:

      • 好的,我解释错了,对不起。内容应该仍然可见,但在容器之外(以 css 为中心固定)。见:jsfiddle.net/6dv41792
      • @jpc 你的意思是你想让它表现得像一个弹出窗口吗?父 div 将具有其原始高度,但内容将固定定位和居中?
      • 是的,这正是我想要实现的目标!
      • @JPC 抱歉回复延迟。您可以尝试我添加的新代码。这将动态收集父 div 的高度,并且只影响其父 div。让我知道这是否适合您。
      • @jpc 很高兴听到这个消息。您可以接受这个答案作为解决方案,以便未来的用户可以找到它。
      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 2018-08-16
      • 2018-05-09
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 2011-02-07
      • 2011-04-15
      相关资源
      最近更新 更多