0

下面的函数在到达页面的 10% 时触发函数 doSomething,但是当您继续滚动时,它会继续触发。我如何让它以 10% 的速度开火并在那之后停止?

一切顺利,

乔伊

  $(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
      }

  });
4

1 回答 1

0

根据浏览器的不同,滚动事件可以触发很多。最好使用计时器。

尝试以下操作:

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);

我希望这有帮助。

于 2012-12-16T01:21:46.790 回答