1

我有如下内容:

<div id="left">
    left
</div>
<div id="right">
    right
</div>

使用 .css 属性:

#left {
    width: 60%;
    float: left
    min-height: ###
    max-height: 1000px;
}
#right {
    width: 40%;
    float: right;
    min-height: ###
    max-height: 1000px;
}

注意这###两个<div>CSSmin-height属性。我想要类似下面的东西(一些伪 JS):

var leftheight = document.getElementById(left);
var rightheight = document.getElementById(right);
if (leftheight.currentHeight > rightheight.currentHeight) {
    rightheight.style.min-height = leftheight.currentHeight;
} else if (rightheight.currentHeight > leftheight.currentHeight) {
    leftheight.style.min-height = rightheight.currentHeight;
}

基本上我想要:

if (current height of left > current height of right) {
    min-height of right = current height of left
} else if (current height of right > current height of left) {
    min-height of left = current height of right
} 
//ie. both left and right have the same min-heights, whichever is larger

我的 Javascript 是错误的,这是我刚刚学习的东西。有没有一种方法可以用来获得我想要的结果?

4

4 回答 4

2

你可以这样做:

if (leftheight.currentHeight > rightheight.currentHeight) {
    rightheight.style.minHeight = leftheight.currentHeight;
} else if (rightheight.currentHeight > leftheight.currentHeight) {
    leftheight.style.minHeight = rightheight.currentHeight;
}

其实minHeight不是min-height

于 2013-10-24T09:28:56.227 回答
1

这里不需要 javascript,您可以通过添加一个容器来实现这一点,并为 div和divoverflow: hidden添加正边距和负边距:leftright

<div id="container">
    <div id="left">left</div>
    <div id="right">right<br /><br /><br /><br />Foobar</div>
</div>
#container {
    width: 75%; /* amend this as required */
    overflow: hidden;
}
#left {
    width: 60%;
    float: left;
    max-height: 1000px;
    background-color: #C00;
    padding-bottom: 1000px;
    margin-bottom: -1000px;
}
#right {
    width: 40%;
    float: right;
    max-height: 1000px;
    background-color: #0C0;
    padding-bottom: 1000px;
    margin-bottom: -1000px;
}

示例小提琴

作为一项规则,javascript绝不应仅用于布局目的。如果有人关闭了 javascript,您的页面会发生什么情况?

于 2013-10-24T09:30:37.513 回答
1

你可以使用jquery

var leftheight = $('#left').height();
var rightheight =$('#right').height();


if (leftheight > rightheight) {
    $('#right').css('min-height',leftheight+"px")
 } 
else if (rightheight > leftheight) {
    $('#left').css('min-height',rightheight + "px")
}
于 2013-10-24T09:33:42.490 回答
1

使用 jQuery

 $(function(){ //ready function to make sure document is ready
 var $leftdiv=$('#left'),
     $rightdiv=$('#right'),
     $leftHeight=$('#left').height(),
     $rightHeight=$('#right').height();
   if ( $leftHeight > $rightHeight) {
      $rightdiv.css('min-height':$leftHeight + "px");
   } else if ( $rightHeight > $leftHeight) {
      $leftdiv.css('min-height':$rightHeight + "px");
   } 
 });
于 2013-10-24T09:30:34.633 回答