I'm looking to have diagonal lines connecting table cells from different rows. I can easily get a diagonal line to connect the corners of a single cell, but is there a way to cross cells?
For example, in the image below, I'd like to have diagonal lines connecting "1 and "3" to the "1 & 3" cell. Same thing with 2, 5, and 2 & 5.
Of course, this is just one variation. I would like to be able to connect any number of cells in any way. Maybe something like this...
Any ideas here?
Try this Demo : Demo
I added one more demo, which will take only the cell positions and based on that it will automatically find the positions and connect them accordingly.
It is better than the other answer, in which we need to provide the line start and end points.
HTML Code
<br>
<table border="1" cellpadding="5">
<tr>
<td>1</td>
<td>+</td>
<td>4</td>
<td>1</td>
<td>+</td>
<td>4</td>
</tr>
<tr>
<td></td>
<td>5</td>
<td></td>
<td></td>
<td>5</td>
<td></td>
</tr>
</table>
CSS Code
.line {
width : 2px;
background-color : red;
display : block;
position : absolute;
-webkit-transform-origin : 0 0;
transform-origin : 0 0;
}
.green {
background-color : green;
}
.blue {
background-color : blue;
}
JavaScript Code
$(function() {
connectCells($('table'), {x : 0, y : 0}, {x : 1, y : 1}, 'red');
connectCells($('table'), {x : 2, y : 0}, {x : 1, y : 1}, 'blue');
});
function connectCells(table, cell1, cell2, cls) {
var td1 = table.find('tr:eq(' + cell1.y + ') td:eq(' + cell1.x + ')');
var td2 = table.find('tr:eq(' + cell2.y + ') td:eq(' + cell2.x + ')');
var pos1 = $(td1).position();
var pos2 = $(td2).position();
drawLine({
x : pos1.left + $(td1).outerWidth()/2,
y : pos1.top + $(td1).outerHeight() - 5
}, {
x : pos2.left + $(td2).outerWidth()/2,
y : pos2.top + $(td2).outerHeight() - 5
}, cls);
}
function drawLine(tp1, tp2, cls) {
if(!cls) { cls = "" };
if(tp2.x < tp1.x && tp2.y < tp1.y) {
p1 = tp2;
p2 = tp1;
} else {
p1 = tp1;
p2 = tp2;
}
var ang = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI - 90;
var lin = $('<span></span>').addClass("line " + cls).appendTo('body');
$(lin).css({
'top' : p1.y,
'left' : p1.x,
'height' : Math.sqrt((p1.x - p2.x)* (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)),
'transform' : 'rotate(' + ang + 'deg)'
});
}