偏移量在标头固定中未定义

offset is undefined in Header Fixed

本文关键字:未定义 偏移量      更新时间:2023-09-26

>我现在有一个代码来修复我的表的标题,它工作正常。但是这个函数有一个警告:

Error: TypeError: $(...).offset(...) is undefined

我的代码(我使用引导):

function goheadfixed(classtable) {
$(classtable).wrap('<div class="fix-inner">'); 
$('.fix-inner').wrap('<div class="fix-outer" style="position: relative;"></div>'); //this is relative cause the header will be absolute
$('.fix-outer').append('<div class="fix-head"></div>');
$('.fix-head').prepend($('.fix-inner').html()); // agrego la tabla
$('.fix-head table').find('caption').remove();
//$('.fix-head table').removeAttr('style');
$('.fix-head table').css('width','100%');
$('.fix-head').css('width', $('.fix-inner table').outerWidth(true)+'px');
$('.fix-head').css('height', $('.fix-inner table thead').outerHeight(true)+'px');
var ithead = parseInt($('.fix-inner table thead').offset().top);
var divfix = parseInt($('.fix-inner').offset().top);
var itop = ithead-divfix;
$('.fix-head').css({'position':'absolute', 'overflow':'hidden', 'top': itop+'px', 'left':0, 'z-index':100 });
$(window).scroll(function () {
    var vscroll = $(window).scrollTop();
    if(vscroll >= ithead)
        $('.fix-head').css('top',(vscroll-divfix)+'px');
    else
        $('.fix-head').css('top', itop+'px');
});
/*  If the windows resize   */
$(window).resize(goresize);
}
function goresize() {
$('.fix-head').css('width', $('.fix-inner table').outerWidth(true)+'px');
$('.fix-head').css('height', $('.fix-inner table thead').outerHeight(true)+'px');
}

我调用我的函数:

goheadfixed('table.fixed');

然后当我把其他代码 javascript 放在下面时,我的代码不起作用,但当放在上面时,它工作正常!

如何删除此警告?

编辑(添加作为答案发布的详细信息):哦。对不起,我忘了说"警告"仅在我不使用该功能时才出现。

如果我调用 funcion goheadfixed('table.fixed'); 好吧,但是如果我不调用这个函数,就会显示警告。

在第 14 行,$('.fix-inner table thead') 要么指不存在的元素,要么是隐藏的元素。听起来好像你找到了至少一个display:none集合的元素,因此它返回了一个未定义的数字。

要解决此问题,您可以为每个元素添加可见的选择器$("thead:visible")