setInterval()导致我的页面滞后

时间:2012-11-19 08:16:39

标签: jquery scroll setinterval lag

我需要继续检查文档的滚动位置。我的代码目前是:

setInterval(function(){ check() }, 1000);
function check() {
    if ($(document).scrollTop()  >700) {
       // do something, like drop down a menu or whatever
    }
    if ($(document).scrollTop() <= 700) {
       // do something
    }
}

这使我的网页非常滞后。有没有其他方法来检查用户使用较少资源的滚动位置?

1 个答案:

答案 0 :(得分:3)

window对象有一个onScroll事件,您可以监听。例如:

var $document = $(document);
$(window).bind('scroll', function() {
  if ($document.scrollTop() > 700) {
    // do something
  } else {
    // do something else
  }
});

另请注意,存储$(document)的返回值并重新使用它会略微提高性能。