如何根据元素位置调用函数?

时间:2019-11-07 23:05:37

标签: javascript html css

我是Java的新手。我正在尝试根据元素在屏幕上的位置进行样式更改,但是我对如何使其工作一无所知。

我要做的是,一旦元素到达页面顶部(并在向上滚动时返回到未设置状态),则使该元素的背景变得固定。到目前为止,我最终得到了这段代码,但是正如您所知,它仅在单击时才触发。我的问题是,一旦用户简单地向上滚动到我想要的位置,我应该使用哪个事件使其生效?

const page2 = document.getElementById("about");

page2.addEventListener("click", bgFixer);

function bgFixer() {
    rect = this.getBoundingClientRect();
    if (rect.top <= 0) {
        var style = document.createElement('style');
        document.head.appendChild(style);
        style.sheet.insertRule('.page-2{background-attachment: fixed}')
    }
}

提前谢谢!提醒我,我真的很新,所以解释越详细越好。

2 个答案:

答案 0 :(得分:1)

您可以通过检查包含元素的scrollTop来测试滚动距离。

如果“粘性”元素的顶部与scrollTop之间的距离等于或小于0,请通过添加带有position: fixed; top: 0px;的类来固定“粘性”元素

由于上述更改了“粘滞”元素的位置,因此我们要存储原始top的距离,因此我们知道,当scrollTop的距离小于原始{ {1}}距离,我们删除了该类。

top

let el = document.querySelector.bind(document),

  c = el("#test"),
  t = el("#toTop");


c.addEventListener("scroll", function() {

  // get inner top distance
  let ttop = t.getBoundingClientRect().top;
  // get container scroll distance
  let ctop = c.scrollTop;

  // if the initial top distance isn't set, set it
  if (!this.init) this.init = ttop;

  // if the inner top is less than or equal to 0 ( no distance )
  // and the container scroll is greater than the initial top distance
  if (ttop <= 0 && ctop >= this.init) {

  // make fixed
    t.classList.add("stuck")
  } else {

  // remove fixed class
    t.classList.remove("stuck");
  }
});
let el = document.querySelector.bind(document),

  c = el("#test"),
  t = el("#toTop");


c.addEventListener("scroll", function() {

  // get inner top distance
  let ttop = t.getBoundingClientRect().top;
  // get container scroll distance
  let ctop = c.scrollTop;

  // if the initial top distance isn't set, set it
  if (!this.init) this.init = ttop;

  // if the inner top is less than or equal to 0 ( no distance )
  // and the container scroll is greater than the initial top distance
  if (ttop <= 0 && ctop >= this.init) {
  
  // make fixed
    t.classList.add("stuck")
  } else {
  
  // remove fixed class
    t.classList.remove("stuck");
  }
});
body,
html {
  height: 100%;
  box-sizing: border-box;
  margin: 0;
}

#test {
  height: 50%;
  overflow-y: scroll;
  box-sizing: border-box;
}

#toTop::before {
  position: absolute;
  content: "";
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  box-shadow: 0 -1px red;
}

#toTop {
  position: relative;
  background: black;
  color: white;
  top: 300px;
  height: auto;
  width: 100%;
  padding: 0;
  margin: 0;
}

#toTop.stuck {
  position: fixed;
  top: 0px;
}

#after {
  height: 1200px;
}

答案 1 :(得分:1)

现在position: sticky;可以很容易地做到这一点,当它位于仅在CSS中定义的fixed时,它将在statictop: 0;之间改变。

详细了解粘性定位:https://www.w3schools.com/howto/howto_css_sticky_element.asp

 .top {
  position: sticky;
  top: 0;
  background: red;
 }
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis feugiat lacus. Etiam mollis odio ipsum, et lobortis dolor fermentum gravida. Praesent volutpat metus quis venenatis venenatis. Sed semper pharetra nibh. In hac habitasse platea dictumst. Duis egestas felis ac maximus iaculis. Nulla quis metus condimentum, porta mi sed, convallis risus. Nulla vehicula lorem elit, eu pulvinar velit pretium quis. Maecenas vitae pulvinar massa. Morbi congue erat vitae pharetra faucibus.</p>
  
<p class="top">top</p>
  
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis feugiat lacus. Etiam mollis odio ipsum, et lobortis dolor fermentum gravida. Praesent volutpat metus quis venenatis venenatis. Sed semper pharetra nibh. In hac habitasse platea dictumst. Duis egestas felis ac maximus iaculis. Nulla quis metus condimentum, porta mi sed, convallis risus. Nulla vehicula lorem elit, eu pulvinar velit pretium quis. Maecenas vitae pulvinar massa. Morbi congue erat vitae pharetra faucibus.</p>
  
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis feugiat lacus. Etiam mollis odio ipsum, et lobortis dolor fermentum gravida. Praesent volutpat metus quis venenatis venenatis. Sed semper pharetra nibh. In hac habitasse platea dictumst. Duis egestas felis ac maximus iaculis. Nulla quis metus condimentum, porta mi sed, convallis risus. Nulla vehicula lorem elit, eu pulvinar velit pretium quis. Maecenas vitae pulvinar massa. Morbi congue erat vitae pharetra faucibus.</p>
  
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis feugiat lacus. Etiam mollis odio ipsum, et lobortis dolor fermentum gravida. Praesent volutpat metus quis venenatis venenatis. Sed semper pharetra nibh. In hac habitasse platea dictumst. Duis egestas felis ac maximus iaculis. Nulla quis metus condimentum, porta mi sed, convallis risus. Nulla vehicula lorem elit, eu pulvinar velit pretium quis. Maecenas vitae pulvinar massa. Morbi congue erat vitae pharetra faucibus.</p>