【问题标题】:resizing divs with jquery crashes window使用 jquery 崩溃窗口调整 div 的大小
【发布时间】:2015-10-28 01:23:25
【问题描述】:

我已将我的页面分成三个 div,并尝试使用 jquery 设置它们的尺寸,以便每个 div 始终与窗口大小相同。

我的代码正在运行,但在几个连续的窗口调整大小后,div 调整大小开始滞后。调整窗口大小的次数越多,这种延迟就会越来越大,直到浏览器窗口出现崩溃。

我可以做些什么来使调整大小更平滑并防止崩溃?

这是我的代码:

$(document).ready(function() {

  sectionSize()

  function sectionSize() {

    var w = []
    var h = []

    var docWidth = $(window).width()
    var docHeight = $(window).height()

    w.push(docWidth);
    h.push(docHeight);

    $(".section").css({
      "height": h,
      "width": w
    });

    $(window).on('resize', function() {
      w.push(docWidth);
      h.push(docHeight);
      sectionSize()
    });
  }

})
body {
  margin: 0;
}
.section {
  position: relative;
}
.section p {
  position: absolute;
  bottom: 5px;
  left: 45%;
}
#top {
  background-color: blue;
}
#middle {
  background-color: red;
}
#bottom {
  background-color: green;
}
<!DOCTYPE html>
<html>

<head>

  <link rel="stylesheet" type="text/css" href="style.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="script.js"></script>


</head>

<body>

  <div class="section" id="top">
    <p>next</p>
  </div>

  <div class="section" id="middle">
    <p>next</p>
  </div>

  <div class="section" id="bottom">
    <p>next</p>
  </div>

</body>

</html>

【问题讨论】:

  • 在你的代码改变大小之前,你需要注销resize handler,等resize完成后再注册。
  • 你每次都在创建一个嵌入式函数,而且每次你​​都在推送一堆数组,看起来它会像疯了一样泄漏内存。
  • 我怀疑这可能是杰夫的问题,不过我还是个初学者,不知道如何解决它。杰夫 - 谢谢你的提示,我一定会调查的。

标签: javascript jquery html css responsive-design


【解决方案1】:

你不能只使用 CSS height:100vh; 吗?将其应用于.section

这是一个小提琴:http://jsfiddle.net/gsgoruja/1/

【讨论】:

  • 设置宽度似乎没有必要,因为它是一个默认为 100% 的块级元素。
【解决方案2】:

&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; 在您的 html 的 head 标签中。

在 css 中使用媒体查询 -

@media screen and (max-width: 400px) {
        .section{
           height : 100px;
           width : 400px;
        }
      }

@media screen and (min-width:450px){
    .section{
       height : //change your css accordingly
       width : //change your css accordingly
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 2012-04-07
    • 1970-01-01
    相关资源
    最近更新 更多