简体   繁体   English

滚动条高度指示器执行功能

[英]Scrollbar height indicator to execute function

I'm using jQuery to get user's current height, and after he reaches that height, there will be animation function (Such as reactive websites, when user scroll down he has animation in different part of the page).我正在使用jQuery获取用户当前的高度,当他达到该高度后,就会有动画功能(例如反应式网站,当用户向下滚动时,他在页面的不同部分有动画)。

Yet, I can't really figure out why exactly the following code doesn't work.然而,我真的不明白为什么下面的代码不起作用。

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

    if(height  > 200) {
      $("#project").animate({
        bottom: '250px',
        opacity: '0.5',
        height: '1000px',
        width: '100%'
      });
    }
});

CSS: CSS:

/*       About Page        */
.about{
  width: 100%;
  height: 1000px;
  background-color: blue;
}
/*       Projects Page        */
.project{
  background-color: red;
}

HTML: HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script src="jquery-3.4.1.min.js"></script>
    <script src="myscripts.js"></script>
    <title>My Portfolio</title>
  </head>
  <body>
    <div id="about" class="about">

    </div>
    <div id="project" class="project">

    </div>
  </body>
</html>

How can I use scrolling height indicator to activate functions such as animation?如何使用滚动高度指示器激活动画等功能?

You need to take into account the height of each section and calculate the scrollBottom position instead, which might be more useful if you want to trigger an animation once you reach some element:您需要考虑每个部分的高度并计算scrollBottom位置,如果您想在到达某个元素后触发动画,这可能更有用:

 const $about = $('#about'); const $projects = $('#projects'); const $services = $('#services'); // Calculate the top offset of each section (number of sections above it * 1000px each). // We want to expand them when we are 50px above them, so we substract that. let projectTop = 1000 - 50; let servicesTop = 2000 - 50; $(window).scroll(() => { requestAnimationFrame(() => { // Calculate the scrollBottom by summing the viewport's height: const scrollBottom = $(window).scrollTop() + $(window).height(); if (scrollBottom >= projectTop) { $projects.animate({ height: '1000px' }); } if (scrollBottom >= servicesTop) { $services.animate({ height: '1000px' }); } }); });
 body { margin: 0; } .about { background: red; width: 100%; height: 1000px; } .projects { background: green; width: 100%; } .services { background: blue; width: 100%; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="about" class="about"></div> <div id="projects" class="projects"></div> <div id="services" class="services"></div>

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

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