演示: https ://so.lucafilosofi.com/jquery-width-returning-incorrect-values-on-table-cells/
这是您几乎重写的插件...在IE7-10、Chrome、Firefox上测试
(function($) {
$.fn.stickyHeader = function() {
return this.each(function() {
// apply to tables only
if (this.tagName.toUpperCase() !== 'TABLE')
return;
var $table = $(this).addClass('jq-stickyHeader-table');
var $wrapper = $table.wrap('<div/>').parent().addClass('jq-stickyHeader-wrapper');
// set each TH to its own width
$table.find('thead th').each(function() {
$(this).html('<div>' + $(this).text() + '</div>');
$(this).width($(this).find('div').width());
});
$wrapper.width($table.width()).height($table.height());
// clone entire table and remove tbody (performance seems fine)
var $stickyheader = $table.find('thead').clone().wrap('<table/>').parent().addClass('jq-stickyHeader');
// hack for IE7
if ($.browser.msie && parseInt($.browser.version, 10) == 7) {
$table.find('tr:first-child td').css('border-top', 0);
}
$stickyheader.css({
'width' : $table.width(),
}).insertAfter($table);
$(window).scroll(function() {
// while over the table, show sticky header
var currTop = ($(this).scrollTop() - $table.offset().top);
$stickyheader.stop(true, true).animate({
top : currTop
}, 100);
var scrollLimit = $table.offset().top + ($table.height() - $stickyheader.height());
var isVisible = (currTop > $table.offset().top && currTop < scrollLimit) ? 'block' : 'none';
$stickyheader.css({
display : isVisible
});
});
});
};
})(jQuery);
$(function() {
$('table').stickyHeader();
});
css里面的demo源码!