【问题标题】:How can i update counter once when window is reached to page?当窗口到达页面时,如何更新计数器一次?
【发布时间】:2023-02-02 01:20:42
【问题描述】:

实际上我没有任何源代码,因为我不知道该怎么做。

请帮助我,你能回答我的问题吗?我会重复“我怎样才能更新计数器一次当窗口到达部分时?”,没有图书馆。

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

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

【问题讨论】:

  • 请更新您尝试过的代码和 HTML 以及该代码给您带来的挑战。我添加了一个 sn-p 来帮助您入门。

标签: javascript html updating


【解决方案1】:

此代码侦听窗口上的滚动事件,一旦窗口的当前滚动位置 scrollPos 大于或等于页面上节 sectionTop 的位置,计数器计数器就会加 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);
  }
});

【讨论】: