在JavaScript中设置DIV高度

时间:2014-10-23 06:16:15

标签: javascript html5

我已经创建了一个jsFiddle来说明我对某些图片的问题:

http://jsfiddle.net/77r41c5j/

双列布局的HTML如:

            <div style="">
                <div id="divContactTexas" style="width: 50%; float: left; background-color: red;">
                    Lorem ipsum 
                    <img src="http://brownfieldsubslab.com/texas.gif" />
                </div>
                <div id="divContactCalifornia" style="width: 50%; float: left; background-color: blue;">
                    Lorem ipsum 
                    <img src="http://brownfieldsubslab.com/california.gif"/>
                </div>
            </div>


            var texasHeight = document.getElementById('divContactTexas').scrollHeight;
            console.log("texasHeight:"+texasHeight);
            var californiaHeight = document.getElementById('divContactCalifornia').scrollHeight;
            console.log("californiaHeight:"+californiaHeight);
            var maxHeight = (texasHeight>californiaHeight) ? texasHeight : californiaHeight;
            console.log("maxHeight:"+maxHeight);    
            document.getElementById('divContactTexas').style.height=maxHeight+'px';
            document.getElementById('divContactCalifornia').style.height=maxHeight+'px';

我在实际网站上有一个模型页面: http://brownfieldsubslab.com/contact.html

那么我主要在Chrome中遇到麻烦,当我改变浏览器窗口的大小时,当浏览器窗口的宽度很小时,某些点上的图像开始变得越来越窄,主要是在Chrome中切断。我已尝试只添加更多像素到它确实可以缓解问题的高度,但我想知道为什么图像被切断是否有办法防止这种情况?

问题开始如下:

enter image description here

我已经尝试过调查一下scrollHeight或者使用哪个高度似乎并不重要。它必须是别的东西。

谢谢

1 个答案:

答案 0 :(得分:1)

http://jsfiddle.net/77r41c5j/4/embedded/result/

http://jsfiddle.net/77r41c5j/4/

function fixHeight(){
    //normalize to check
    document.getElementById('divContactTexas').style.height='auto';
    document.getElementById('divContactCalifornia').style.height='auto';

    var texasHeight = document.getElementById('divContactTexas').scrollHeight;
    console.log("texasHeight:"+texasHeight);
    var californiaHeight = document.getElementById('divContactCalifornia').scrollHeight;
    console.log("californiaHeight:"+californiaHeight);
    var maxHeight = (texasHeight>californiaHeight) ? texasHeight : californiaHeight;
    console.log("maxHeight:"+maxHeight);    
    document.getElementById('divContactTexas').style.height=maxHeight+'px';
    document.getElementById('divContactCalifornia').style.height=maxHeight+'px';
}

window.onload = fixHeight;
window.onresize = fixHeight;

将代码包装在一个函数中,并在调整窗口大小时调用它,最初在窗口加载时调用它。

对于图像截止,请使用css。

#left-side-image{
  width: 100%;
  max-width: 212px;
}

使用CSS http://jsfiddle.net/77r41c5j/5/embedded/result/

http://jsfiddle.net/77r41c5j/5/