Javascript:使两个div相同的高度

时间:2017-01-19 03:19:47

标签: javascript

警告:我不是开发人员。

this site,我遇到一个问题,即滑块的高度与div右边的div的高度不匹配:

<div id="front-page-slide">
    <div id="slider">[rev_slider alias="home"]</div>
    <div id="boxes">
        <table width="459" border="0" cellspacing="0" cellpadding="0">
          <tr>
            <td bgcolor="#8A0E02" style="color: #FFF; padding: 1em; font-size: 1em;">Freightplus know what they are doing. I was very satisfied with their work and will use them for any further freight needs. 
              <br />
              <br />
            -Customer 1</td>
          </tr>
          <tr>
            <td><iframe src="https://player.vimeo.com/video/43915936?title=0&byline=0&portrait=0" width="459" height="auto" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></td>
          </tr>
          <tr>
            <td><img src="http://freightplus.com/beta/wp-content/uploads/2017/01/freight-plus-map.jpg" alt="Freight Plus" /></td>
          </tr>
          <tr>
            <td><img src="http://freightplus.com/beta/wp-content/uploads/2017/01/freight-plus2.jpg" alt="Freight Plus" /></td>
          </tr>
        </table>
    </div>.
</div>

<script type="text/javascript">
    var left=document.getElementById('slider').style.height;
    var right=document.getElementById('boxes').style.height;
    if(left>right) {
        document.getElementById('boxes').style.height=left;
    }
    else {
        document.getElementById('slider').style.height=right;
    }
</script>

上面的Javascript在HTML代码之后触发,但没有生效。

2 个答案:

答案 0 :(得分:2)

左右将是'',因为这些div都没有任何内联样式

您需要使用getBoundingClientRect

var left=document.getElementById('slider').getBoundingClientRect().height;
var right=document.getElementById('boxes').getBoundingClientRect().height;
if(left>right) {
    document.getElementById('boxes').style.height=left + 'px';
}
else {
    document.getElementById('slider').style.height=right + 'px';
}

答案 1 :(得分:0)

似乎你的style.height对于滑块和方框div都是空的,请改用clientHeight。使用window.onload函数确保代码在元素加载后运行。

<script type="text/javascript">
    window.onload = function() {
        var left=document.getElementById('slider').clientHeight;
        var right=document.getElementById('boxes').clientHeight;
        if(left>right) {
            document.getElementById('boxes').style.height=left+"px";
        }
        else {
            document.getElementById('slider').style.height=right+"px";
        }
    };
</script>