我如何触发一个javascript来调整DIV的大小,使其尽可能快地工作



我将使用以下脚本:

<script type="text/javascript">
    window.document.onload = function(e){
        var aheight = document.getElementById("a").offsetHeight;
        var bheight = document.getElementById("b").offsetHeight;
        if(aheight > bheight) {
            document.getElementById("b").offsetHeight = aheight;
        }else {
            document.getElementById("a").offsetHeight = bheight;
         }
    }
</script>

HTML:

<div>
    <div id="a" class="grid_6" style="background-color: #ff00ff">
        <div class="block-border">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </div>
    </div>
    <div id="b" class="grid_6" style="background-color: #ffff00">
        <div class="block-border">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
        </div>
    </div>
</div>

和CSS:

.grid_6 {
    width: 200px;
    display:inline;
    float: left;
    margin-left: 0.99%;
    margin-right: 0.99%;
}

我将使用它来均衡页面上两个DIV之间的高度。有人能告诉我这个剧本最好放在哪里吗?这样它能尽快发挥作用。window.document.onload也是最好的触发器吗?我可以在加载了元素id"a"one_answers"b"的DIV上触发吗?我只是想避免用户看到DIVS的变化是大小。

虽然表中的表中有空单元格作为填充是不好的,但使用与表相关的CSS是非常好的。考虑这个仅CSS的解决方案:

<div id="parent">
    <div class="grid_6">
        <!-- content -->
    </div>
    <div class="grid_6">
        <!-- content -->
    </div>
</div>

CSS:

#parent{
  display: table-row
}
.grid_6{
  display: table-cell
  width: 50%;
}

Fiddle:http://jsfiddle.net/NqXgd/

注意,不必存在具有display: table的元素;浏览器将自动插入一个匿名元素。您也可以编写#parent{display:table},并在样式为div的单元格周围插入一个匿名table-row

请注意,如果您没有设置明确的宽度,浏览器可以自由选择它们(例如,使高度相等)。这可能是有益的,或者您可以显式设置一些宽度来约束布局。

偏移量大小是只读的,要更改脚本中的高度,需要将元素的样式.height设置为偏移量+'px'。

如果ab的大小不依赖于外部资源,那么您不必等待load事件,您可以简单地将其放在正文的末尾(或任何可能影响ab大小的元素定义之后的任何位置):

<script type="text/javascript">
var aheight = document.getElementById("a").offsetHeight;
var bheight = document.getElementById("b").offsetHeight;
if(aheight > bheight) {
    document.getElementById("b").style.height = aheight+'px';
}else {
    document.getElementById("a").style.height = bheight+'px';
 }
</script>

演示

请注意,我将offsetHeight =更改为style.height =,因为您无法更改元素的offsetHeight

最新更新