jquery css高度设置不正常

时间:2010-09-20 04:15:32

标签: jquery css height

我正在尝试使用一些jQuery将我的产品和目录页面的左右列(类为.columns)设置为#detail <div>的高度它从SQL数据库中提取了一些数据。

所以,我正在使用这个jQuery代码:

$(document).ready(function() {

  detailHeight = $('#detail').css('height');
  columnHeight = detailHeight + 10;

  $('.columns').css('height', columnHeight 'px');

});

我的页面在这里:http://www.marioplanet.com/product.asp?IDnum=1

出于某种原因,高度不合适......

关于为什么的任何想法?

谢谢!

4 个答案:

答案 0 :(得分:7)

你这里有一个错字:

$('.columns').css('height', columnHeight 'px');

+缺失:

$('.columns').css('height', columnHeight + 'px');

但是,正如其他人所指出的,使用css()函数来访问元素的高度对于代码来说是错误的,因为它返回并期望在数值之后具有CSS单元的字符串。因此,您并不是真正添加数字而是连接字符串。这就是你的代码不起作用的原因。

要修复代码,请使用jQuery的便捷方法height()来获取和设置元素的高度作为数值。在设置时,只需将您的号码作为参数传递:

  detailHeight = $('#detail').height();
  columnHeight = detailHeight + 10;

  $('.columns').height(columnHeight);

答案 1 :(得分:1)

您是否尝试过.height()甚至.attr("height")

答案 2 :(得分:1)

$(document).ready(function() {

  detailHeight = $('#detail').css('height'); // would return something like 25px...
  columnHeight = detailHeight + 10; // 25px + 10 == ??

  $('.columns').css('height', columnHeight + 'px'); // ===>> .css('height', '25px10' + 'px');

});

建议,

$(document).ready(function() {

  detailHeight = $('#detail').height(); // use .height()
  columnHeight = detailHeight + 10; 

  $('.columns').css('height', columnHeight + 'px');

});

答案 3 :(得分:1)

由于每个人都提到了最后一个语句中缺少的“+”符号,但是当我在变量columnHeight上运行alert()时(使用我的示例),它显示了20px10。我将一个detailHeight包装在一个parseInt()中,然后就可以了。

HTML代码段


<div id="detail" style="background:#aaa;">HELLO</div>
<div id="x" class="columns" style="background:#f00;">HELLO</div>

JS片段


$(document).ready(function() {
  detailHeight = $('#detail').css('height');
  columnHeight = parseInt(detailHeight) + 10;

  $('.columns').css('height', columnHeight+'px');
});