问题
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.
An approach is simple, it’s just 1.5 lines of code:
$('.inbox').scroll(function() {
$(this).find('.inbox-headers').css('top', $(this).scrollTop());
});
Demo.
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.
回答1:
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:
- In your case,
position: fixed;
might be a good alternative. - 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.
- 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).
回答2:
function debounce(func, wait) {
var timeout;
return function() {
var context = this,
args = arguments,
later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
$('.inbox').scroll(debounce(function() {
$(this).find('.inbox-headers').css('top', $(this).scrollTop());
}, 100));
This is a little debounce function I use a lot in situations like this.
回答3:
The best way to do static header is to strictly separate the header and the body of table:
Then you should apply a overflow:scroll style to .body DIV only
- No absolute positioning
- No scroll events
If you table is very wide then in any case you need use scroll events
来源:https://stackoverflow.com/questions/11075525/jquery-s-css-lags-when-applied-on-scroll-event