Can't set DIV equal to another DIV HTML/Javascript

你离开我真会死。 提交于 2019-12-20 02:56:20

问题


for some reason, my wrapper div won't equal the same height as my maincontent div. I'll post the code and I would love if someone could help me understand why. Also, I can use jquery if need be

Javascript:

var wrap=document.getElementById('wrapper');
var left=document.getElementById('maincontent').style.height;

wrap.style.height=left;



HTML:

<div id="wrapper">

    <!-- TemplateBeginEditable name="Main Content" -->

    <div id="maincontent">

    </div>

    <!-- TemplateEndEditable --><!-- TemplateBeginEditable name="Background image" -->

    <div id="image" style="background-image: ;">

    </div>

回答1:


I don't know if I have guessed right, but . . .

One possible cause of what you describe is the presence of a float instruction in the maincontent DIV.

See this jsFiddle example

In the example, the wrapper DIV is the wrong height -- it ignores the presence of the maincontent DIV, and the maincontent DIV appears to be below it.

This is caused by the float:left instruction in the maincontent DIV. A float will remove that DIV from the HTML flow, and the parent DIV will be missing that height. In fact, the maincontent DIV is overflowing the wrapper DIV.

SOLUTION:

Place a overflow:hidden or overflow:auto on the parent DIV (that is, on the wrapper DIV).

See this jsFiddle demo of the solution


Note:

position:absolute and position:fixed will also remove DIVs out of the flow. However, they cannot be "fixed" by using overflow:________. Manually setting the height of the containing DIV, or using javascript or some other wizardry may be necessary.




回答2:


1- If you wan to get the rendered height of element use one of the clientHeight or offsetHeight or scrollHeight instead of style.height

2- make sure that wrapper has closing tag </div>

3- when setting height of element don't forget "px" after height value.

4- If you have images without height set for them in your div, you have to wait for images to be loaded before triggering height function. you may use $(window).load or some other methods...




回答3:


You should know the difference between ele.style.height and ele.clientHeight.

I wrote a demo here,

http://jsbin.com/ninure/edit?html,css,js,console,output

May it help.



来源:https://stackoverflow.com/questions/34573227/cant-set-div-equal-to-another-div-html-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!