简体   繁体   English

在 HTML 页面上显示某个部分时运行 JS

[英]Run JS when show a certain section on HTML page

I have a JavaScript TypingText.js that executes "typing text", however, I need to run JavaScript "typing text" when a user scrolls to the section where that text is located.我有一个执行“输入文本”的 JavaScript TypingText.js ,但是,当用户滚动到该文本所在的部分时,我需要运行 JavaScript“输入文本”。 Can anyone help me?谁能帮我?

 <section id="mysection"> <div id="example1">My text here</div> </section> <script type="text/javascript"> // Flag to execute the function only once let typeTextStarted = false; // Get the section<s position in the document let mysectionPosition = $("#mysection").offset() // Get the view port height let viewportHeight = $(window).height(); $(window).on("scroll", function() { // If scrolled position is more than the section's position MINUS the viewport height if ($(this).scrollTop()>mysectionPosition.top - viewportHeight && !typeTextStarted) { // Set flag typeTextStarted = true; new TypingText(document.getElementById("example1")); TypingText.runAll(); } }); </script>

First, you have to detect when the section is visible.首先,您必须检测该部分何时可见。 So a bit of calculations are required.所以需要一些计算。 That is:那是:

  1. To get the section's position in the document获取该部分在文档中的位置
  2. To get the viewport height获取视口高度
  3. On scroll, get the scrolled position在滚动时,获取滚动位置

Then, using a flag, run the function once...然后,使用标志,运行该函数一次...

Tested on CodePenCodePen 上测试

// Flag to execute the function only once
let typeTextStarted = false;

// Get the section<s position in the document
let mysectionPosition = $("#mysection").offset()

// Get the view port height
let viewportHeight = $(window).height();

$(window).on("scroll", function() {

  // If scrolled position is more than the section's position MINUS the viewport height
  if ($(this).scrollTop()>mysectionPosition.top - viewportHeight && !typeTextStarted) {

    // Set flag
    typeTextStarted = true;

    new TypingText(document.getElementById("example1"));
    TypingText.runAll();
  }
});

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

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