6

私が書いているプラ​​グインでは、表のセルの幅にひどい問題があります。jQuery の.width()関数を使用してテーブル セルの幅を取得し、同じセルを返された幅に設定するだけです。基本的に、これは:

$table.find('> thead > tr > th').each( function() {
    var $th = $(this);
    $th.css({width: $th.width()});
} );

ただし、多くの場合、返される幅は正しくなく、設定するとセルの幅が変更されます。最初は 1px ずれているように見えたので、返された幅に 1px を追加しました。ただし、境界線が太い場合はさらにずれますが、単に境界線の幅を追加するだけではないようです。まず、明らかに 2 つの境界線がありますが、1 つの境界線の幅だけずれています。また、さまざまな境界線の幅を使用すると、追加する必要がある値はほぼランダムに見えます。

これが私のコードの例です- 幅設定部分はページ読み込みの 1 秒後に実行されるので、変更を確認できます。Javascriptでテーブルセルの幅を取得/設定する信頼できる方法はありますか?

4

1 に答える 1

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!

于 2012-11-25T00:33:37.647 に答える