简体   繁体   English

jQuery:从顶部+元素高度查找元素位置以激活addClass

[英]Jquery: find element position from top + element height to activate addClass

Jquery beginner here. jQuery的初学者在这里。

I'm currently using the below script in order to find an element and then add/remove a class based on the scroll position from said element. 我目前正在使用以下脚本来查找元素,然后根据所述元素的滚动位置添加/删除类。

I'm trying to make my fixed navigation icon change colour when over the dark background. 我试图使固定的导航图标在黑暗背景下更改颜色。

Currently my code says find element 1 and then addClass to element 2 when the user scrolls 1000px after the element is found. 当前,我的代码说找到元素1,然后在用户找到元素后滚动1000px时将addClass添加到元素2。 It works but isn't ideal as the page is responsive and the sections change height. 它可以工作,但不是理想的,因为页面具有响应能力并且各部分会更改高度。

You can see here, section 2 is the white section below the top section: http://leebuckle.co.uk/ 您可以在此处看到,第2部分是顶部下面的白色部分: http : //leebuckle.co.uk/

Id like find the height of section 2 and then add the class once the user scrolls the height of section 2. So it would be +(section_2 height) rather than +1000px 我想找到第2部分的高度,然后在用户滚动第2部分的高度后添加类。因此它将是+(section_2 height)而不是+ 1000px

Thanks in advance! 提前致谢!

$(document).ready(function(){
  var div = $("#section_2");
  var pos = div.position();

$(window).scroll(function () {
  var windowpos = $(window).scrollTop();

  if (windowpos >= (pos.top + 1000)) {
    $( "#nav-icon span" ).addClass("black_menu");
  }

 else {
    $( "#nav-icon span" ).removeClass("black_menu");
  }

  });
});

You can use offset from jQuery to get the position of an element from the top of the document. 您可以使用jQuery的offset来从文档顶部获取元素的位置。

So your line that has 所以你的线有

if (windowpos >= (pos.top + 1000)) { ...

May look something like: 可能看起来像:

if (windowpos >= (div.offset().top)) { ...

使用jQuery的.offset()获取section2 + .height()的顶部位置,以动态获取section2的高度。

if (windowpos >= (div.offset().top + div.height()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM