使用javascript对象根据行中的第一个div设置所有div的高度相似

时间:2016-12-24 18:52:08

标签: javascript arrays object

我有三个div p, p1, p3,它位于div r内,高度不同 我想在div中设置所有div,类似于r中的第一个div,根据它们的类名使用object:

var firstChild = document.querySelector(".r:first-child");
var descendant = firstChild.querySelectorAll(".p, .p2,.p3");
var p, p2, p3;
[].forEach.call(descendant, function(itm) {
  itm.style.backgroundColor = "green";
  var ch = document.getElementsByClassName("p");
  for (var i = 0; i < ch.length; i++) {
    var ar = ['p', 'p2', 'p3']; //are the class name 
    p = ch[i].parentNode.clientHeight / 1.5; // height value for p 
    p2 = ch[i].parentNode.clientHeight + p; // height value for p2 
    p3 = p2 / 1.5; // height value for p3 
    var colors = {}; //using dynamic 
    colors[ar[0]] = p;
    colors[ar[1]] = p2;
    colors[ar[2]] = p3;
    ch[i].style.height = colors[ch[i].className] + "px"; //problem comes here this shows undefined
    itm.style.height = ch[i].clientHeight + "px";
    document.getElementById('demo').innerHTML = "asfaf";
  }
});
.p,
.p2,
.p3 {
  display: inline-block;
  width: 80px;
  border: 1px solid #999;
}
.p {
  height: 50px;
}
p2 {
  height: 100px;
}
p3 {
  height: 150px;
}
<div>
  <div class="r">
    <div class="p">fgdsgs</div>
    <div class="p2">sdgdfg</div>
    <div class="p3">sdgdfg</div>
  </div>
</div>
<p id="demo"></p>

正如您所看到的p, p1, p2在javascript中有不同的值,我想让所有div都处于相同的高度

示例=如果r中的第一个div是p,那么r中的所有div将根据它们描述的值(ch[i].parentNode.clientHeight / 1.5)i javascript,类似地,如果第一个div是p3则所有div({{1内部r将获得javascript中描述的相同高度p, p2, p3  使用动态propery对象,我的代码中出现了什么问题?

演示= https://jsfiddle.net/m2gj5dt5/

1 个答案:

答案 0 :(得分:1)

我要做的是,我会得到最大的高度并将其设置为所有p标签。

&#13;
&#13;
var firstChild = document.querySelector(".r > :first-child");
var descendant = document.querySelectorAll(".p, .p2, .p3");
var p, p2, p3;
for (var el = 0; el < descendant.length; el++) {
  debugger;
  var itm = descendant[el];
  itm.style.backgroundColor = "green";
  debugger;
  var ch = document.getElementsByClassName("p");
  for (var i = 0; i < ch.length; i++) {
    var ar = ['p', 'p2', 'p3'];
    p = ch[i].parentNode.clientHeight / 1.5;
    p2 = ch[i].parentNode.clientHeight + p;
    p3 = p2 / 1.5;
    var colors = {};
    colors[ar[0]] = p;
    colors[ar[1]] = p2;
    colors[ar[2]] = p3;
    debugger;
    ch[i].style.height = colors[ch[i].className] + "px";
    itm.style.height = ch[i].clientHeight + "px";
    document.getElementById('demo').innerHTML = "asfaf";
  }
}
&#13;
.p, .p2, .p3 {
  display: inline-block;
  width: 80px;
  border: 1px solid #999;
}
&#13;
<div>
  <div class="r">
    <div class="p">fgdsgs</div>
    <div class="p2">sdgdfg</div>
    <div class="p3">sdgdfg</div>
  </div>
</div>
<p id="demo"></p>
&#13;
&#13;
&#13;

另外,您忘记了.p2的CSS中的p3

小提琴:https://jsfiddle.net/qsj1444p/