jQuery width()在表格单元格上返回不正确的值

时间:2012-11-24 23:51:15

标签: jquery html-table width

在我正在编写的插件中,我遇到了表格单元宽度的可怕问题。我所做的就是使用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中表格单元格的宽度?

1 个答案:

答案 0 :(得分:1)

  

演示: http://so.devilmaycode.it/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里面的演示源!