我有jQuery代码:
$('td').hover(function () {
var t = $(this),
index = t.index(); // the position of the TD in the row, so you can find the one below it
t.addClass('hovered'); // apply hovered class to this TD...
t.nextAll(':lt(3)').addClass('hovered'); // ...and to the TD next to it...
t.closest('tr')
.nextAll(':lt(3)')
.find('td:eq(' + index + ')')
.addClass('hovered')
.nextAll(':lt(3)')
.addClass('hovered'); // ...and to the 2 below
}, function () {
// remove the hovered class when no longer hovering
$(this).closest('table').find('td').removeClass('hovered');
});
如何选择4x4细胞?不像演示那样2x4 +2。
答案 0 :(得分:1)
$('td').hover(function () {
var t = $(this),
index = t.index(); // the position of the TD in the row, so you can find the one below it
t.addClass('hovered'); // apply hovered class to this TD...
t.nextAll(':lt(1)').addClass('hovered'); // ...and to the TD next to it...
t.closest('tr').nextAll(':lt(1)').find('td:eq(' + index + ')').addClass('hovered').nextAll(':lt(1)').addClass('hovered'); // ...and to the 2 below
}, function () {
// remove the hovered class when no longer hovering
$(this).closest('table').find('td').removeClass('hovered');
});
我将lt(3)更改为lt(1)。看看这是不是你想要的。
答案 1 :(得分:1)
尝试
$('td').hover(function () {
var t = $(this),
index = t.index(); // the position of the TD in the row, so you can find the one below it
t.addClass('hovered'); // apply hovered class to this TD...
t.nextAll(':lt(3)').addClass('hovered'); // ...and to the TD next to it...
t.closest('tr').nextAll(':lt(3)').each(function(i,v){
$('td:eq(' + index + ')', this).addClass('hovered').nextAll(':lt(3)').addClass('hovered'); // ...and to the 2 below
})
}, function () {
// remove the hovered class when no longer hovering
$(this).closest('table').find('td').removeClass('hovered');
});
演示:Fiddle
更简化的版本
$('td').hover(function () {
var t = $(this),
index = t.index(); // the position of the TD in the row, so you can find the one below it
var trs = t.closest('tr').nextAll(':lt(3)').addBack();
trs.find('td:eq(' + index + ')').add(trs.find('td:gt(' + (index) + '):lt(3)')).addClass('hovered');
}, function () {
// remove the hovered class when no longer hovering
$(this).closest('table').find('td').removeClass('hovered');
});
演示:Fiddle
答案 2 :(得分:0)
var selectY = 4, selectX = 4
$('td').hover(function () {
var $cell = $(this),
$table = $cell.parents("table"),
x = $cell.index(),
y = $cell.parent().index();
$table.find("tr:eq("+y+"),tr:gt("+y+"):lt("+(selectY-1)+")")
.find("tr:eq("+x+"),td:gt("+x+"):lt("+(selectX-1)+")")
.addClass("hovered");
}, function(){
$(this).parents("table")
.find("td")
.removeClass("hovered");
});
您也可以使用selectX和Y vars选择您的区域
*已更新,因为gt似乎不接受-1:/