javascript 当窗口到达页面时,我如何更新计数器?

rekjcdws  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(105)

实际上我没有任何源代码,因为我不知道怎么做。
请帮助我,你能回答我的问题吗?我将重复"当窗口到达节时,我如何更新计数器一次?"

/* sample JavaScript tried here */
/* related CSS */

.oops {
  border: solid red 1px;
}
<div class="oops"> HTML I tried here</div>
r1zk6ea1

r1zk6ea11#

此代码侦听窗口上的scroll事件,并在窗口scrollPos的当前滚动位置大于或等于页面上sectionTop节的位置时将计数器counter递增1。然后删除事件侦听器以防止计数器再次递增。

// initialize the counter to zero
var counter = 0;

// get the section element
var section = document.querySelector("#section");

// get the position of the section on the page
var sectionTop = section.offsetTop;

// listen to the scroll event on the window
window.addEventListener("scroll", function() {
  // get the current scroll position of the window
  var scrollPos = window.scrollY;
  
  // check if the window has reached the section
  if (scrollPos >= sectionTop) {
    // increment the counter by 1
    counter++;
    
    // prevent the counter from being incremented again
    window.removeEventListener("scroll", arguments.callee);
  }
});

我想这对你来说是个好的开始

相关问题