0

我有一个 div,它的内容服务器在表中动态生成。我需要在表格顶部有最后一行,我用 CSS 做到了。但是,当内容增加它的高度时,第四行会覆盖第一行。HTML 如下所示:

<div class="main">
<table id="news">
<tr id="tr1">
<td id="td1">
<fieldset id="fieldset1">Content</fieldset>
</td>
</tr>
<tr id="tr2">
<td id="td2">
<fieldset id="fieldset2">Content</fieldset>
</td>
</tr>
<tr id="tr3">
<td id="td3">
<fieldset id="fieldset3">Content</fieldset>
</td>
</tr>
</table>
</div>

CSS:

.main { padding-top: 150px; } /* Making room for 3rd row */
#tr3 { margin-top: -500px; } /* Move it above the other rows */

我需要的是找到#tr3 的高度并将这个值传递给.main 的填充和#tr3 的margin-top 的方法。我试图从通过搜索找到的解决方案中整理出一些东西,但我的知识并没有那么广泛,我想出的是:

var tr3Height = document.getElementById('#tr3').clientHeight;
var mainPadding = document.getElementById('.main');

function SetAttribute (ObjectID, Value) { 
   document.getElementById('.main').style.paddingTop = tr3Height + "px";
   document.getElementById('#tr3').style.marginTop = -(500 + tr3Height) + "px";
}

我很确定这是应该如何完成的,但我不知道如何完成它。也许有人可以帮助我朝着正确的方向前进。谢谢你。

编辑:我忘了提:我不能改变 .main div 中的 HTML,因为是服务器生成的。

4

1 回答 1

1

当前问题:

  • 您有多个元素使用相同的 ID。ID 应该始终是唯一的。
  • getElementById('#tr3')是无效的。
  • getElementById('.main')也是无效的。
  • 您不能marginTop在显示为table-cell.
  • 您实际上并没有调用您的函数(并根据您在页面加载时想要的评论来判断)

解决方案(按上述顺序):

  • 将标记中的所有重复 ID 更改为唯一。
  • 这应该是getElementById('tr3')
  • main用ID替换类main并使用getElementById('main').
  • 我真的不明白你想用这部分实现什么(目前无论如何)......
  • 如果您想加载它,则不需要单独的功能,只需使用 w indow.onload = function()..

这将解决您的负载和填充问题(请注意,我已将标记更改为具有唯一 ID - 检查下面的 jsFiddle),尽管正如您在评论中看到的那样,您的边距更改在注册时将不起作用:

window.onload = function(){
   var tableRow3Height = document.getElementById('tableRow3').clientHeight;
   console.log(tableRow3Height); // returns 42
   document.getElementById('main').style.paddingTop = tableRow3Height + "px";
   var tableRow3 = document.getElementById('tableRow3');
   tableRow3.style.marginTop = -500 + tableRow3Height + "px";
   console.log(tableRow3.style.marginTop) // returns -458px, although it won't do anything.
};

jsFiddle 示例在这里。

于 2013-06-13T22:32:25.807 回答