减少对.resize和.scroll方法的调用次数 [英] reduce number of calls for .resize and .scroll methods

查看:118
本文介绍了减少对.resize和.scroll方法的调用次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码找出查看者正在访问页面的哪一部分(类似于Google图书,以找出正在查看的页面):

I'm using the following code to find out which part of the page the viewer is visiting (something like google books, to find out the page that's being viewed) :

$("#main-content").scroll(function () { 
            Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
            window.location.hash = "#"+Nx.curPage;
            Nx.select(undefined);
        });

在另一部分中,我使用$(window).resize( ... )将内容调整为当前窗口大小,每次调整大小都会调用该大小.正如您可以想象的那样,这会减慢很多页面的速度,尤其是在较旧的硬件上.有什么方法可以停止滚动或调整大小然后开始执行工作,从而减少进程数量?类似于$("#main-content").scrollStop ???

also in another part I use $(window).resize( ... ) to fit my content in current window size, which is called for every single resize . as you can imagine this slows down the page alot, specially on older hardwares. Is there any way to realise when scrolling or resizing is stopped and then start doing the stuff, so number of processes is reduced ? something like $("#main-content").scrollStop ???

推荐答案

您可以做两件事.

1.).设置超时时间,以便仅在某些空闲状态之后才进行大小调整/滚动:

1.) Set up a timeout so that resize/scroll only happens after some idle state:

var timeout;
$("#main-content").scroll(function () { 
    clearTimeout(timeout);
    timeout = setTimeout(function(){
      Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
      window.location.hash = "#"+Nx.curPage;
      Nx.select(); // note: undefined is passed by default
    }, 200);
});

2.)限制通话次数/秒:

var lastScroll = 0;
$("#main-content").scroll(function () { 
  var now = +new Date;
  if (now - lastScroll > 100) { // only execute if (elapsed > 100ms)
    Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
    window.location.hash = "#"+Nx.curPage;
    Nx.select();
    lastScroll = now;
  }          
});

这篇关于减少对.resize和.scroll方法的调用次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆