我想更改行内的所有div类似于row2
的第一个孩子的高度,如果类在行之外,div高度将是自动而不是更改。 我的代码中的问题是什么,任何人都可以解释我也不想从css中更改它。
var lgh , lgh_in,mdh,mdh_in,smh,smh_in;
var r = ".row2 >";
var z = ['.lg','.lg-in','.md','.md-in','.sm','.sm-in',];
z.forEach(function (x){
var xx = document.querySelectorAll( r + x );
for ( var j = 0; j < xx.length; j++) {
var ch = document.getElementsByClassName('row2');
for(var i = 0 ; i < ch.length ; i++ ){
var ar = ['lg','lg-in','mdh','md-in','sm','sm-in']; //these are class names , if I put this into my div the div height should be change according to mdh ,lgh ,smh .... etc
for(var k = 0; k < ar.length;k++){
if(ch[i].firstChild.className === ar[k]){
lgh = ch[i].parentNode.clientHeight/ 1.5 ;
lgh_in = ch[i].parentNode.clientHeight - lgh ;
mdh = lgh/ 1.5 ;
mdh_in = ch[i].parentNode.clientHeight - mdh ;
smh = mdh/ 1.5 ;
smh_in = ch[i].parentNode.clientHeight - smh ;
var colors = {};
colors[ar[0]] = lgh;
colors[ar[1]] = lgh_in;
colors[ar[2]] = mdh;
colors[ar[3]] = mdh_in;
colors[ar[4]] = smh;
colors[ar[5]] = smh_in;
ch[i].firstChild.style.height = mdh + "px"; //if I remove the px then output is different also
document.getElementById('demo').innerHTML = mdh ; // only for output checking
if (ch[i].parentNode.tagName === "BODY") {
ch[i].style.height = "auto"; // if the div2 parent is body then height will be auto.
}
}
}
}
}
});
所以我可以更改第一个子div,但我无法更改row2
里面的所有div,这是我的问题,
HTML
<div class="main"><div class="row2"><div class="lg">xfghjgjgx</div><div class="lg-in">xfgvcbvx</div></div>
<div class="row2"><div class="lg-in">xfghjgjgx</div><div class="lg">xfgvcbvx</div></div>
答案 0 :(得分:0)
Jquery更容易..我做这样的事情吗?
// For each .box element
$('.box').each(function() {
// Set up the variables
var $this = $(this),
w = $this.find('img').width(), // Width of the image inside .box
h = $this.find('img').height(); // Height of the image inside .box
$this.width(w).height(h); // Set width and height of .box to match image
});
答案 1 :(得分:0)
所有块的高度相同的变体(https://jsfiddle.net/br3t/fmovbtp1/)
var classes = ["lg", "lg-in", "md"];
var requiredHeight = window.getComputedStyle(document.querySelector(".row2 .lg")).height;
classes.forEach(function(cls) {
document.querySelectorAll("." + cls).forEach(function(item) {
item.style.height = requiredHeight;
});
});