首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使此函数在滚动窗口/文档的10%处触发?

如何使此函数在滚动窗口/文档的10%处触发?
EN

Stack Overflow用户
提问于 2012-12-16 08:38:00
回答 1查看 67关注 0票数 0

当下面的函数达到页面的10%时,它会触发函数doSomething,但当您继续滚动时,它会继续触发。我如何让它以10%的速度发射一次,然后停止发射?

万事如意,

乔伊

代码语言:javascript
复制
  $(document).scroll(function(e){

      // grab the scroll amount and the window height
      var scrollAmount = $(window).scrollTop();
      var documentHeight = $(document).height();

      // calculate the percentage the user has scrolled down the page
      var scrollPercent = (scrollAmount / documentHeight) * 100;

      if(scrollPercent = 10) {
          // run a function called doSomething
          doSomething();
      }

      function doSomething() { 
            $(".fill").append('<img src="img/arrow-down.png"/>');

          // do something when a user gets 10% of the way down my page
      }

  });
EN

回答 1

Stack Overflow用户

发布于 2012-12-16 09:21:47

根据浏览器的不同,scroll事件可能会触发很多次。最好使用计时器。

尝试以下操作:

代码语言:javascript
复制
var  didScroll = false;
var doneAction = false;

$(window).scroll(function() {
    didScroll = true;
});

setInterval(function() {
    if ( didScroll ) {
      didScroll = false;

      // grab the scroll amount and the window height
      var scrollAmount = $(window).scrollTop();
      var documentHeight = $(document).height();

      // calculate the percentage the user has scrolled down the page
      var scrollPercent = (scrollAmount / documentHeight) * 100;

      if(scrollPercent >= 10 && !doneAction) {
          alert('You just scrolled to 10 percent.'); // or whatever action you want to perform
          doneaction = true;
      }
    }
}, 250);

我希望这能帮到你。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13897531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档