2016-02-05 69 views
1

我想获得表格单元格的位置/偏移量,然后使用这些数据我想追加并在同一个位置放置一个新元素。获取表格单元格在溢出元素内的位置

的代码来实现,这是如下:

function addBlock() 
{ 
    // get the cell position 
    var cellPosition = $('.item').position(), 
     cellPositionTop = cellPosition.top, 
     cellPositionLeft = cellPosition.left; 

    // append the overlay 
    var blockOverlay = $('<div class="blockOverlay"></div>').appendTo('.container').hide(); 

    // set the overlay width and height to the same as the cell 
    blockOverlay.css({ 
     'background-color':'blue', 
     'width': $('.item').outerWidth(), 
     'height': $('.item').outerHeight() 
    }); 

    // position the overlay in the same place as the cell 
    blockOverlay.css({ 
     'position': 'absolute', 
     'top': cellPositionTop, 
     'left': cellPositionLeft 
    }); 

    // show the overlay 
    blockOverlay.show(); 
} 

含有细胞的表是相当大的,坐在溢流元件意味着表格单元可屏幕之外的内部。如果上面的代码运行时没有滚动,那么它工作正常,但是如果我滚动然后运行它,偏移量是不正确的。这是因为即使我使用的是position()而不是offset(),它在获取调用函数时相对于其父级(.container)的单元格位置,而不考虑其滚动位置。

我该如何解决这个问题?

这里是一个小提琴,显示问题:https://jsfiddle.net/25e6qmnh/

尝试点击各个滚动位置的按钮,你会看到蓝色方块永远只能覆盖红细胞在起始位置时。无论滚动位置如何,它总是应该覆盖红色单元格。

回答

3

您需要添加$('.container').scrollLeft()cellPositionLeft,因此新生产线将是这样的:

cellPositionLeft = cellPosition.left + $('.container').scrollLeft(); 

你不计算与滚动宽度的位置,所以你需要添加它。您还需要与scrollTop()一样执行相同的操作,但这将留给您。

这里是一个工作示例:https://jsfiddle.net/qorpucwq/

+0

当然!感谢这一点,完美的作品! – Cameron

+1

@Cameron:您需要对scrollTop执行相同的操作 –

2

您可以初始化元素.item的值一次,然后它工作正常。

function addBlock() 
{ 
    // get the cell position 
    var 
     cellPositionTop = cellPosition.top, 
     cellPositionLeft = cellPosition.left; 

    // append the overlay 
    var blockOverlay = $('<div class="blockOverlay"></div>').appendTo('.container').hide(); 

    // set the overlay width and height to the same as the cell 
    blockOverlay.css({ 
     'background-color':'blue', 
     'width': $('.item').outerWidth(), 
     'height': $('.item').outerHeight() 
    }); 

    // position the overlay in the same place as the cell 
    blockOverlay.css({ 
     'position': 'absolute', 
     'top': cellPositionTop, 
     'left': cellPositionLeft 
    }); 

    // show the overlay 
    blockOverlay.show(); 
} 
var cellPosition; 
$(document).ready(function(){ 
    cellPosition = $('.item').position(); 
    $('.clickme').on('click', function(e){ 
     e.preventDefault(); 
     addBlock(); 
    }); 

}); 

这里是工作fiddle