2016-03-18 3 views
-1

Как вы выделяете ячейки в таблице HTML, позволяя пользователю выбирать их - точно так же, как в Excel?Как выделить ячейки в таблице HTML

Вот 3 образца, которые показывают, что я имею в виду: enter image description here

+0

Вы можете использовать JavaScript, чтобы сделать это. Чтобы сохранить выбранные позиции ячейки, используйте localStorage. – mehulmpt

+0

отлично, Mehul - пожалуйста, покажи мне, как –

ответ

1

Это одна из возможности:

<table> 
<tr> 
<td>...</td> 
<td>...</td> 
</tr> 
... 
</table> 

И JavaScript:

function toggleBG() { 
    if(this.className.indexOf("yellowBG") >= 0) { 
     var x = this.className; 
     this.className = x.split("yellowBG").join(''); 
    } else { 
     this.className += "yellowBG"; 
    } 
} 
var elem = document.getElementsByTagName('td'); 
for (var i = 0; i < elem.length; i++) { 
    elem[i].addEventListener('click', toggleBG,, false); 
} 

И CSS:

.yellowBG { 
    background: yellow; 
} 
0

Вам просто нужно применить класс CSS, когда пользователь нажимает на ячейку. Вы можете удалить класс после второго щелчка.

Попробуйте это:

// Wait until the DOM is loaded 
 
window.addEventListener("DOMContentLoaded", function(){ 
 

 
    // Get all the td elements in an array 
 
    var theCells = document.getElementsByTagName("td"); 
 
    
 
    // Loop through each td 
 
    for(var i = 0; i < theCells.length; ++i){ 
 
    
 
    // Set up a click event handler for the td 
 
    theCells[i].addEventListener("click", function(){ 
 
     
 
     // Check to see if the td has the class attribute applied already 
 
     if(this.getAttribute("class") === "highlight"){ 
 
     // If so, remove it 
 
     this.removeAttribute("class"); 
 
     } else { 
 
     // If not, add it 
 
     this.setAttribute("class", "highlight");  
 
     } 
 
    }); 
 
    } 
 
    
 
});
td{border:1px solid black;} 
 
.highlight {background:#ff0;}
<table> 
 
    <tr> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    </tr> 
 
    <tr> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    </tr> 
 
    <tr> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    </tr> 
 
    <tr> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    <td>...</td> 
 
    </tr> 
 
</table>

Смежные вопросы