helloworld1234 helloworld1234 - 1 month ago 13
HTML Question

Highlight cell border color when click, change back when click to others

I have the code below:



function highlight(cell){
cell.style.borderColor = "red";
}

function originalColor(cell){
cell.style.borderColor = "black";
}

td{
cursor: pointer;
}

<table border="1">
<tr>
<td onmousedown="highlight(this);" onblur="originalColor(this);">Cell 1</td>
<td onmousedown="highlight(this);" onblur="originalColor(this);">Cell 2</td>
<td onmousedown="highlight(this);" onblur="originalColor(this);">Cell 3</td>
</tr>
<tr>
<td onmousedown="highlight(this);" onblur="originalColor(this);">Cell 4</td>
<td onmousedown="highlight(this);" onblur="originalColor(this);">Cell 5</td>
<td onmousedown="highlight(this);" onblur="originalColor(this);">Cell 6</td>
</tr>
<tr>
<td onmousedown="highlight(this);" onblur="originalColor(this);">Cell 7</td>
<td onmousedown="highlight(this);" onblur="originalColor(this);">Cell 8</td>
<td onmousedown="highlight(this);" onblur="originalColor(this);">Cell 9</td>
</tr>
</table>





It will highlight the border to red when click, when click to the other cell, it suppose change back to black color, but it doesn't work, I try
onmouseup
,
onmouseover
, it doesn't work as what I want.

The technique I'hv tried is using
tabindex
, it works; but that can highlight one cell, if I try to select 2 cells at the same time, it doesn't work. Anyone can help?

Answer
    var redNow = 1;
    function highlight(cell) {
        redNow == 1 ? redNow = 0 : redNow.style.borderColor = "black";
        redNow = cell;
        cell.style.borderColor = "red";
    }
    td {
    		cursor: pointer;
    	}
   <table border="1">
    <tr>
        <td onmousedown="highlight(this);">Cell 1</td>
        <td onmousedown="highlight(this);">Cell 2</td>
        <td onmousedown="highlight(this);">Cell 3</td>
    </tr>
    <tr>
        <td onmousedown="highlight(this);">Cell 4</td>
        <td onmousedown="highlight(this);">Cell 5</td>
        <td onmousedown="highlight(this);">Cell 6</td>
    </tr>
    <tr>
        <td onmousedown="highlight(this);">Cell 7</td>
        <td onmousedown="highlight(this);">Cell 8</td>
        <td onmousedown="highlight(this);">Cell 9</td>
    </tr>
</table>
Comments