Outer element margin not equal to inner element margin

孤者浪人 提交于 2020-01-05 02:35:08

问题


I am using an Android WebView to display my app's HTML content. I need to dynamically find the full height of an element (usually a div) including padding, margin, and border. I am using JavaScript, and cannot use jQuery.

I have been using scrollHeight on my div to get the height. I got the computed style of the div using var style = window.getComputedStyle(DIV, null); and got the top and bottom margin by calling style.marginTop and style.marginBottom. They were both 0px. The problem is that scrollHeight still does not account for the height of the margins belonging to div's.

I got the child elements of my div (usually a P or H* tag) and obtained the same fields the same way: scrollHeight, marginTop, and marginBottom. The scrollHeights are the exact same (as I usually only have one child per div), but there is usually a top or bottom margin value in the child that is not reflected in the parent element.

I don't really understand why this is so. It appears as through the child's margin is rendered outside of parent, but the parent has no knowledge of it, and cannot directly access it.

I am looking for a way to access the margin defined by the child through the parent element. Is that possible?

This Question was very helpful, but I did not find an underlying reason for why it is rendered this way and the thread seems to have grown cold.

Thanks!


回答1:


Sime Vidas pointed me in the right direction, so thanks!

I found myself trying to find out the exact height of the collapsed margins between divs and their children (but worded it much differently in my question). When accessing that information trough the DOM it will tell me style attributes of the parents and children, but it does not report the height of any collapsed margins.

So...the real answer to my question is NO. I have not been able to find a way to directly access the attribute of the collapsed margins.

What is just as good is taking the offsetTop attribute of my div, and finding the difference between the offsetTop attribute of the next Div. That gives the total height including final rendering of margins. To find the margins only, subtract the scrollHeight.

This may not work in all scenarios, but was more than enough for my purposes.



来源:https://stackoverflow.com/questions/12431434/outer-element-margin-not-equal-to-inner-element-margin

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