Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当元素的直接子元素具有上/下边距时,getBoundingClientRect()返回错误_Javascript_Html_Css - Fatal编程技术网

Javascript 当元素的直接子元素具有上/下边距时,getBoundingClientRect()返回错误

Javascript 当元素的直接子元素具有上/下边距时,getBoundingClientRect()返回错误,javascript,html,css,Javascript,Html,Css,HTML <body> <div id='el1'> <div class='directChildren' style='width:50%;height:100px;float:left;margin-top:0'> .... </div> </div> <div id='el2'> <div class='directChildren' style='width:50%;he

HTML

<body>
  <div id='el1'>
   <div class='directChildren' style='width:50%;height:100px;float:left;margin-top:0'>
    ....
   </div>
  </div>
  <div id='el2'>
   <div class='directChildren' style='width:50%;height:100px;float:right;margin-top:20px'>
    ....
   </div>
  </div>
  <div style='clear:both'/>
</body>
问题:
两个div(el1,el2)具有相同的顶部坐标,但为什么getBoundingClientRect返回不同的值呢?。这种情况也发生在页边距底部。

因为CSS没有正确定义。您正在对内部元素(.directChildren)使用浮点,而不是在#el1和#el2上使用它,而没有正确清除父元素上的浮点行为。这就是为什么边距顶部的效果溢出父维度的原因

使用下面的HTML和CSS更容易获得正确的结果,我使用了flex,使用了适当的样式。如果需要,也可以使用浮动

<div class="container">
  <div id='el1'>
    <div class='directChildren' style='height:100px;margin-top:0'>
      ....
    </div>
  </div>
  <div id='el2'>
    <div class='directChildren' style='height:100px;margin-top:20px'>
      ....
    </div>
  </div>
</div>

对不起,代码已被编辑,请重新审阅。这就是我之前的意思。@Kardinata在回答问题后请不要更改,因为这会使答案无效。改为问一个新的后续问题。我将把问题回滚到原来的版本。
<div class="container">
  <div id='el1'>
    <div class='directChildren' style='height:100px;margin-top:0'>
      ....
    </div>
  </div>
  <div id='el2'>
    <div class='directChildren' style='height:100px;margin-top:20px'>
      ....
    </div>
  </div>
</div>
.container {
  display: flex;
}
.container .directChildren {
  flex: 1;
}