.resize()性能改进

时间:2019-07-15 16:41:54

标签: javascript jquery

我有一个关于jQuery调整大小性能的简单问题。

我编写了以下代码:

console.clear();

$(document).ready(function() {
  const header = $("header").height();
  const hero = $(".hero__video");
  let resizeTimer;

  function resizeHeader() {
    hero.css("margin-top", `-${header}px`);
  }
  resizeHeader();

  function resizeFunction() {
    const currentHeight = $("header").height();

    if (header !== currentHeight || header == currentHeight) {
      hero.css("margin-top", `-${currentHeight}px`);
    }
  }

  // For performance purposes, put a timeout on running the resize function
  $(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resizeFunction, 200);
  });
});
ul {
  display: flex;
  list-style: none;
  margin: 0;
}
ul li {
  align-items: center;
  display: flex;
}

h1,
p {
  color: white;
}

.hero {
  position: relative;
}
.hero .hero__video {
  background-image: url("https://wallpaperplay.com/walls/full/f/2/0/187247.jpg#.XSyQe4Pfm0k.link");
  background-size: cover;
  height: 100vh;
  position: relative;
  width: 100%;
  z-index: -1;
}
.hero .hero__text {
  left: 50%;
  margin-left: -88px;
  margin-top: -99px;
  position: absolute;
  top: 50%;
}
.hero .hero__text .text {
  text-align: center;
}

.content__news {
  background-color: lightblue;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header class="container">
  <nav class="row justify-content-center">
    <div class="logo mr-md-auto mr-lg-5"><a href="#"><img src="https://via.placeholder.com/325x70" alt=""/></a></div>
    <ul class="nav py-3 ml-lg-5">
      <li class="nav-item mx-2"><a href="#">About XYZ</a></li>
      <li class="nav-item mx-2"><a href="#">Buy XYZ</a></li>
      <li class="nav-item mx-2"><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>
<section class="container-fluid px-0 hero">
  <div class="hero__video"></div>
  <div class="hero__text">
    <div class="text my-5">
      <h1>Welcome</h1>
      <p>Lorem Ipsum dolor sit amet.</p>
    </div>
  </div>
</section>
<section class="container">
  <div class="row">
    <div class="content__news">
      <h2>Happenings at XYZ</h2>
    </div>
  </div>
</section>

,想知道此方法是否固有错误或臭味?目的是要获得一个全角,全高的背景图像,并在其上方放置一个导航栏。根据窗口大小,导航栏的大小将有所不同,并且背景图像的页边距顶部将必须进行相应调整以匹配大小差异。

CodePen

0 个答案:

没有答案