简体   繁体   中英

How to set a div height according to another div height using javascript?

I have 2 divs. Since div 1 could be longer, ie infinite scroll div, I want to make div 2 the same height with div 1 using javascript. I tried to use the code below, but it does not work. Why?

javascript:

<script type="text/javascript">
document.getElementById("div2").setAttribute("height",document.getElementById("div1").clientHeight);
</script>

my divs:

#div1 {
width: 700px;
background: #FFF;
overflow: hidden;
float: left;
}

#div2 {
width: 300px;
background-image: url(../images/user_panel.png);
background-repeat:repeat-y;
}

What about this:

var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
div2.style.height = div1.style.height; // Might have to add +"px" here.

Just from the top of my head.

the setAttribute function is a DOM function to add a new attribute to an HTML element. You are trying to add the height on a div. That would have the effect:

<div id="div2" height="...">...</div>

But HTML does not define such an height HTML element attribute.

What you are looking for is to set the style of the DOM element. That would be the style DOM element property. And inside the style you have the height property that you must set:

document.getElementById("div2").style.height = document.getElementById("div1").clientHeight + "px";

In the above code sample you might also think about div1 's padding (probably bringing it into the computation). This is because clientHeight includes the padding but style.height does not.

这应该可以解决问题:

document.getElementById("div2").style.height=document.getElementById("div1").clientHeight+'px';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM