如果我滚动得太快,滚动链接定位将不起作用。有没有更好的方法?

时间:2019-04-02 01:13:39

标签: javascript css scroll

我正在尝试制作一个标题,该标题在顶部,左侧和右侧都有边距,直到被滚动为止,此时它应该平稳地增长直到不再有边距为止。

我已经用'position:sticky'照顾了页边距,并尝试使用滚动链接定位来逐渐增加页眉的水平。

HTML

<header id = "header">
  <h1>Hi there</h1>
</header>

JS

  window.onscroll = function() { /* wait until page loaded */
     var margin = 15;
     var borderOffset = 1.875; /* 15/8 */
    var scrollStatus = window.pageYOffset;
    var header = document.getElementById("header");

    if (scrollStatus <= margin) {
      header.style.marginLeft = (margin - scrollStatus) + "px";
      header.style.marginRight = (margin - scrollStatus) + "px";
      header.style.borderRadius = ((margin - scrollStatus) / borderOffset) + "px";
    }
  };

CSS

header {
  background-color: blue;
  margin: 15px;
  position: sticky;
  top: 0;
  border-radius: 8px;
  padding: 8px;
}

codepen:https://codepen.io/anon/pen/yryZBb

但是,当我滚动页面太快时,标题不会完全增长。我该如何工作?

2 个答案:

答案 0 :(得分:1)

如果您不想要JQuery:

let header = document.getElementById("header");
let nav = document.getElementById("nav");

window.addEventListener("scroll", function ()
{
    let marginTop = 10;

    if (window.scrollY >= (header.clientHeight + marginTop))
    {
        nav.style.position = "fixed";
        nav.style.width = "100%";
        nav.style.margin = "0";
    }
    else
    {
        nav.style.position = "";
        nav.style.width = "";
        nav.style.margin = "";
    }
});
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body { height: 1200px; }
img { width: 100%; }

#header { background: #a3b0b0; }
#nav { background: #cad7d7; padding: 8px; top: 0; margin: 10px 40px; }

ul { margin: 0; padding: 0; list-style: none; }
ul li { display: inline; }
<header id="header">
    <img src="https://www.lagaleramagazine.es/rucab/img/1400_slider1.jpg">
</header>
<nav id="nav">
    <ul>
        <li>Home</li>
        <li>About</li>
        <li>Contact</li>
    </ul>
</nav>

答案 1 :(得分:0)

所以我刚刚添加了

  else {
  header.style.marginLeft = "0";
  header.style.marginRight = "0";
  header.style.borderRadius = "0";
}

紧接if (scrollStatus <= margin) {...}之后,以确保标头完全增长。可能不是执行此操作的最佳方法,因此我暂时不会将其标记为已接受。