jQuery width() 在表格单元格上返回不正确的值
Posted
技术标签:
【中文标题】jQuery width() 在表格单元格上返回不正确的值【英文标题】:jQuery width() returning incorrect values on table cells 【发布时间】:2012-11-12 20:50:19 【问题描述】:在我正在编写的插件中,我在表格单元格的宽度方面遇到了可怕的问题。我所做的就是使用 jQuery 的 .width()
函数获取表格单元格的宽度,然后 将同一单元格设置为返回的宽度。基本上是这样的:
$table.find('> thead > tr > th').each( function()
var $th = $(this);
$th.css(width: $th.width());
);
但是,在许多情况下,返回的宽度不正确,设置它会更改单元格的宽度。起初它看起来好像偏离了 1px,所以我在返回的宽度上添加了 1px。但是如果边框更厚,它会关闭更多 - 但是它似乎不是简单地添加边框宽度的情况。对于初学者来说,显然有 2 个边框,但仅相差 1 个边框的宽度。并且随着边框宽度的变化,您需要添加哪个值似乎几乎是随机的。
Here's an example with my code - 宽度设置部分在页面加载后运行 1 秒,因此您可以看到更改。是否有可靠的方法来获取/设置 javascript 中表格单元格的宽度?
【问题讨论】:
对于您想要的粒度级别,可能最好远离表格,使用DIV
和 css display:table-cell
也许你应该试试.outerWidth()
? api.jquery.com/outerWidth
@charlietfl 不会达到完全相同的结果吗?
@D.Strout outerWidth 返回包括填充和两个边框的宽度 - 将单元格设置为该宽度会使其更宽。
表格很古怪...看看 googleDocs 电子表格或像slickgrid 这样的网格系统...他们使用DIV
。我最近读了一些关于你完全相同的问题的试验和磨难,同时对 css box-sizing
属性进行了一些学习。
【参考方案1】:
演示: 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!
【讨论】:
我不明白,您似乎没有解决任何问题。您仍在将宽度设置为从.width()
返回的值。
是的,但我已经重写了一点你的代码!它对我有用! ;)
对我来说不是 - 我得到了完全相同的结果。而且您似乎包含了我在另一个代码笔中编写的其他一些代码...以上是关于jQuery width() 在表格单元格上返回不正确的值的主要内容,如果未能解决你的问题,请参考以下文章
在uitableview单元格上留下滑动删除按钮打开然后返回导致崩溃