2013-03-20 45 views
0

这可行,但我相信它写得更干净。如何以更复杂的方式编写此代码?

<script> 
$(document).ready(function(){ 
    $('.col').css({'height':($(document).height())+'px'}); 
    $(window).resize(function() { 
    $('.col').css({'height':($(document).height())+'px'}); 
    }); 
} 
</script> 

我试过没有第一$('.col').css...,它不工作。 所以基本上我想告诉浏览器的是:“当文档准备就绪时,调整这个div的大小,并在每次高度变化时不断调整它的大小。”

+1

我没有看到任何方式显著简化JS。你可以探索CSS解决方案。看到这里:http://stackoverflow.com/questions/289409/full-height-css-layout-with-multiple-columns和http://stackoverflow.com/questions/10239534/how-to-have-multiple-columns - 即,消耗-100-高度使用-Twitter的自举。如果只在宽度更改时触发调整大小,则可以提高 – jfriend00 2013-03-20 20:48:27

+0

的性能 – Huangism 2013-03-20 21:01:03

回答

3

这就是:

<script> 
    $(window).resize(function() { 
     $('.col').css({'height':($(document).height())+'px'}); 
    }); 
    $(function(){ 
     $(window).trigger('resize'); 
    }); 
</script> 

您可以收听resize事件并触发它,当文档准备好。

其他小的变化:

  • 可以简化document.ready$(function(){})
  • resize事件侦听器可能会document.ready之前创建的,因为window对象总是存在的,你可以早将事件附加给它你需要。
2

或者另一种变体,带有一点点(我猜)更清晰的语法:

$(window).resize(function() { 
    $('.col').height($(document).height()); 
}).resize();