![](/img/trans.png)
[英]Drag Selection on HTML Table (Square/Rectangle Section with colspan/rowspan)
[英]html table selection with colspan or rowspan
我有一個表,用戶可以用鼠標選擇行和列,然后將選定的區域合並到一個單元格中,它的工作原理類似於ms word表的行為。
但是,當表具有rowSpan或colSpan時,所選區域不是規則矩形,因此我想將選擇范圍擴展到規則矩形,以便以后合並。
這是rowspan和colspan的示例,當選擇不包括TD的行跨度時,它工作正常,否則,選擇是錯誤的。
$('td').mousedown(function () {
$(this).closest('table').find('td').removeClass('selected');
var start = {
x: this.cellIndex,
y: this.parentNode.rowIndex
}
$(this).closest('table').find('td').mouseover(function () {
var x1 = Math.min(start.x, this.cellIndex);
var y1 = Math.min(start.y, this.parentNode.rowIndex);
var x2 = Math.max(start.x, this.cellIndex);
var y2 = Math.max(start.y, this.parentNode.rowIndex);
$(this).closest('table').find('td').each(function () {
var x = this.cellIndex;
var y = this.parentNode.rowIndex;
if (x >= x1 && x <= x2 && y >= y1 && y <= y2) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
}
});
});
var self = this;
$(document).mouseup(function () {
$(self).closest('table').find('td').unbind('mouseover');
$(document).unbind('mouseup');
});
});
當您的單元格的colspan > 1
時,選擇會出錯,因為該單元格之后的單元格的cellIndex
值會更改,以適應上一個單元格采用的colspan
。 請參見下圖。
這是當您使用colspan=2
在單元格的左上角按下鼠標左鍵並將鼠標向下拖動到第三行(用紅線表示)時,單元格選擇邏輯的作用:
colspan=2
的單元格的左上角向下移動。 選擇開始選擇的單元格的cellIndex
和rowIndex
值。 開始cellIndex=2
和rowIndex=0
。 cellIndex=2
和rowIndex=2
[cellIndex,rowIndex]
和結束[cellIndex,rowIndex]
。 在這種情況下,選擇單元格[2,0]
, [2,1]
, [2,2]
。 那就是問題所在! 單元格[2,1]
已移至下一列,以針對colspan=2
的上一個單元格進行調整。 盡管該單元格的cellIndex
值為2
,但您應將其視為其cellIndex
值為3
並將其從選擇中排除。 我已經找到了原因,現在我使用了一個名為cellPos的jQuery插件來解決cellIndex問題。 然而,仍然存在問題,選擇區域可以是非規則矩形。 參見下圖。
第一個圖像顯示選擇區域,箭頭指示鼠標方向。 第二張圖片顯示了我到底是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.