jQuery的css()应用于滚动事件时滞后 [英] jQuery’s css() lags when applied on scroll event

查看:121
本文介绍了jQuery的css()应用于滚动事件时滞后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个简单的固定标题"表.我知道理论上只能用CSS做到这一点,但是就OSX Lion及其消失的滚动条而言,它不能很好地工作.因此,我正在使用jQuery.

I’m trying to implement a simple "fixed headers" table. I know this can in theory be done with CSS only, but it doesn’t work very well when it comes to OSX Lion and its disappearing scrollbars. So I’m doing it with jQuery.

一种方法很简单,只需1.5行代码:

An approach is simple, it’s just 1.5 lines of code:

$('.inbox').scroll(function() {

    $(this).find('.inbox-headers').css('top', $(this).scrollTop());

});

演示 .

Demo.

这在Firefox中工作正常且流畅,但在Webkit浏览器中却严重滞后.为什么会发生这种情况,以及如何优化此代码?或者也许以不同的方式解决问题.

This works fine and smooth in Firefox, but lags horribly in webkit browsers. Why is that happening and how do I optimise this code? Or maybe approach the problem differently.

推荐答案

滚动"事件经常非常被触发.如果要在某些浏览器中滚动时修改DOM,总是很难跟上.

The "scroll" event is fired very frequently. It's always going to be really hard to keep up if you're modifying the DOM while scrolling in some browsers.

您可以做的是以下事情之一:

What you can do is one of these things:

  1. 对于您来说,position: fixed;可能是一个很好的选择.
  2. 如果没有,那么让事件处理程序在将来的100毫秒内启动一个计时器,以取消该过程中以前的任何计时器.这样,只有在滚动停止或暂停后才更新DOM.
  3. 如果要连续更新,请在进行更新时跟踪时间戳,如果少于一定时间(100毫秒或任何时间),则在处理程序中不执行任何操作.
  1. In your case, position: fixed; might be a good alternative.
  2. If not, then have the event handler start a timer for like 100 milliseconds in the future, canceling any previous timer in the process. That way, the DOM will be updated only after scrolling stops or pauses.
  3. If you want continuous updates, keep track of the timestamp when you do an update, and do nothing in the handler if it's been less than some amount of time (100ms or whatever).

这篇关于jQuery的css()应用于滚动事件时滞后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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