jquery - 检查 div 是否有样式高度。如果是,请不要调整高度

标签 jquery css

我有一个固定高度的祖 parent div(直到 css 媒体查询另有决定)。 用户可以输入高度的父 div(主要是百分比值,在极少数情况下是 px 值) 用户可以在其中输入百分比和 px 值的子 div。

我试图完成的事情:

  1. 如果用户没有为父 div 定义值,则所有子 div 都需要遵循其自然内容高度。

  2. 如果用户为父 div 定义了值,但没有为子 div 定义值,则所有子 div 都应平分。

涵盖了 1 和 2。

现在我正在努力解决以下问题:

  1. 如果为父 div 输入了值,则所有子 div 都应平分,但输入值的子 div 除外。该值(value)应得到尊重。

我得到了以下我现在拥有的东西:

http://jsfiddle.net/andyderuyter/qepqdmer/

$('.child').each(function() {

  var aantalDivs = $(".child").length;
  var parentHeight = $(this).parent().height();
  var childNewHeight = parentHeight / aantalDivs;
  var hasHeight = $(this).height().length;

  if (parentHeight == 700) {
    $('.child').height(childNewHeight);
  }

});
.grandparent {
  height: 700px;
}
.parent {
  height: 100%;
  background-color: black;
  text-align: center;
}
.child-1 {
  background-color: orange;
}
.child-2 {
  background-color: purple;
  color: white;
}
.child-3 {
  background-color: violet;
}
.vertical {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="grandparent">
  <div class="parent">
    <div class="child child-1">
      <div class="vertical">Div 1</div>
    </div>
    <div class="child child-2">
      <div class="vertical">Div 2</div>
    </div>
    <div class="child child-3" style="height:25%;">
      <div class="vertical">Div 3</div>
    </div>
  </div>
</div>

最佳答案

假设目标是为所有 div 设置固定高度,不包含在样式标签中设置的直接高度(因此不包括通过 css 设置的任何内容),您可以使用 jquery 属性过滤器,例如 [style* =高度]:

var childdivs = $('.child'); //get all child elements
var height = childdivs.parent().height();
var withheight = childdivs.filter('[style*=height]'); //get all elements with a style tag containing height
withheight.each(function(){height-=$(this).height();}); //subtract those heights from parentheight
var otherdivs = childdivs.not(withheight); //get all other elements (without height tag)
otherdivs.height(height/otherdivs.length); //set all elements to parentheight/otherelementcount

Fiddle

正如其他人所提到的,如果使用类来操纵自定义高度,可能会更好地处理,即使是由用户这样做的,但上面的内容应该适用于特定示例。

关于jquery - 检查 div 是否有样式高度。如果是,请不要调整高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31275665/

相关文章:

html - 将输入字段标记为无效

jquery - IE 7 中的 CSS 菜单中断

javascript - 同步多个带有惯性效果的滚动div

javascript - 在单独的页面上打开剧透

jquery - 如何处理 "The select2(' destroy') 方法在不使用 Select2 的元素上调用”

javascript - 对 json 数据进行分组并对值求和

animation - 多个 css3 转换冲突

css - bootstrap 与 font-awesome 冲突?

jquery append 将内联 li 向下推

javascript - 如何在 Javascript 中分离两个事件