Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

scroll - run a function for each class element when gets into view javascript

I'm trying to build a portfolio site when the main page is a scroll of all the projects. I gave all the titles of the projects a fixed position with display 'none' and I want to change it to display 'block' only when a project section enters the viewport.

The code works! but only for the last class element of all the titles :(

This is how I wrote it, I would appreciate any help!

  var isInViewport = function (elem) {
      var bounding = elem.getBoundingClientRect();
      return (
          bounding.top >= 0 &&
          bounding.left >= 0 &&
          bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
          bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
      );
  };


var projects = document.getElementsByClassName("proj");
for (x=0; x<projects.length; x++){
  var proj = projects[x];
  var head = proj.querySelector('.head');

  console.log(proj);
  window.addEventListener('scroll', function (event) {
      if (isInViewport(proj)) {
          head.style.display = "block"
      } else {
          head.style.display = "none"
          console.log(head);
      };
    }, false);
  };

Thanks!

question from:https://stackoverflow.com/questions/65643594/run-a-function-for-each-class-element-when-gets-into-view-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...