【问题标题】:How to write this in a more sophisticated way? [closed]如何以更复杂的方式编写它? [关闭]
【发布时间】:2013-03-21 04:57:50
【问题描述】:

这行得通,但我确信它写得更干净。

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

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

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

这里是:

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

您可以监听resize 事件并在文档准备好时触发它。

其他小改动:

  • 您可以将document.ready 简化为$(function(){})
  • 可以在document.ready 之前创建resize 事件侦听器,因为window 对象始终存在,您可以在需要时尽早将事件附加到它。

【讨论】:

    【解决方案2】:

    或者另一种变体,语法更简洁一点(我猜):

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

    【讨论】:

      猜你喜欢
      • 2014-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 2011-03-07
      相关资源
      最近更新 更多