Dis*_*oat 6 jquery html-table width
在我写的一个插件中,我遇到了表格单元格宽度的可怕问题.我所做的就是使用jQuery的.width()函数获取表格单元格的宽度,然后将相同的单元格设置为返回的宽度.基本上,这个:
$table.find('> thead > tr > th').each( function() {
var $th = $(this);
$th.css({width: $th.width()});
} );
Run Code Online (Sandbox Code Playgroud)
但是,在许多情况下,返回的宽度不正确,并设置它会更改单元格的宽度.起初它看起来好像被1px关闭所以我在返回的宽度上添加了1px.但是随着边框越来越厚,它越来越多 - 但似乎并不是简单地添加边框宽度的情况.对于初学者来说,显然有2个边框,但它只有1个边框的宽度.并且随着边框宽度的变化,您需要添加几乎随机的值.
这是我的代码示例 - 宽度设置部分在页面加载后运行1秒,因此您可以看到更改.有没有一种可靠的方法来获取/设置Javascript中表格单元格的宽度?
演示: https://so.lucafilosofi.com/jquery-width-returning-in Correct-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();
});
Run Code Online (Sandbox Code Playgroud)
演示源里面有css!