Выделение ячеек таблицы по клику

В продолжении статей о рамках у ячеек таблицы, сделаем их появление по клику с помощью JQuery.

Таблица и основные стили из предыдущих примеров:

<table class="table">
	<thead>
		<tr>
			<th>RU</th>
			<th>FR</th>
			<th>US Men</th>
			<th>US Women</th>
			<th>UK</th>
			<th>Длина</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>35.5 RU</td>
			<td>36</td>
			<td>4</td>
			<td>5</td>
			<td>3.5</td>
			<td>22.1</td>
		</tr>
		<tr>
			<td>36 RU</td>
			<td>36 2/3</td>
			<td>4.5</td>
			<td>5.5</td>
			<td>4</td>
			<td>22.5</td>
		</tr>
		<tr>
			<td>36.5 RU</td>
			<td>37 1/3</td>
			<td>5</td>
			<td>6</td>
			<td>4.5</td>
			<td>22.9</td>
		</tr>
		...
	</tbody>
</table>
HTML
.table {
	border-collapse: collapse;
	border-spacing: 0;
	width: 100%;
}
.table th, .table td {
	border: 1px solid #888;
	padding: 10px;
	text-align: center;
	vertical-align: middle;
	position: relative;
	cursor: pointer;
}
CSS
1
/* Hover */
.table td:hover:after {
	content: '';
	position: absolute;
	top: 0px;
	right: 0px; 
	bottom: 0px;    
	left: 0px;
	border: 3px solid #ffe5c5;
}

/* Click */
.table td.active:after {
	content: '';
	position: absolute;
	top: 0px;
	right: 0px; 
	bottom: 0px;    
	left: 0px;
	border: 3px solid orange !important;
}
CSS
$(document).ready(function(){
	$('.table th, .table td').click(function(){
		$('.table td').removeClass('active');
		$(this).addClass('active');
	});
});
JS

Результат:

2
/* Hover */
.table .hover:after {
	content: '';
	position: absolute;
	top: 0px;
	right: 0px;    
	bottom: 0px;    
	left: 0px;
	height: 105%;
	border-left: 3px solid #ffe5c5;
	border-right: 3px solid #ffe5c5;
}
.table thead .hover:after {
	border-top: 3px solid #ffe5c5;
}
.table tbody tr:last-child .hover:after {
	border-bottom: 3px solid #ffe5c5;
	height: auto;
}

/* Click */
.table .active:after {
	content: '';
	position: absolute;
	top: 0px;
	right: 0px;    
	bottom: 0px;    
	left: 0px;
	height: 105%;
	border-left: 3px solid orange;
	border-right: 3px solid orange;
}
.table thead .active:after {
	border-top: 3px solid orange;
}
.table tbody tr:last-child .active:after {
	border-bottom: 3px solid orange;
	height: auto;
}
CSS
$(document).ready(function(){
	$('.table th, .table td').hover(function(){
		var t = parseInt($(this).index()) + 1;
		$('th:nth-child(' + t + '),td:nth-child(' + t + ')').addClass('hover');
	}, function() {
		var t = parseInt($(this).index()) + 1;
		$('th:nth-child(' + t + '),td:nth-child(' + t + ')').removeClass('hover');
	});

	$('.table th, .table td').click(function(){
		$('.table th, .table td').removeClass('active');
		var t = parseInt($(this).index()) + 1;
		$('th:nth-child(' + t + '),td:nth-child(' + t + ')').addClass('active');
	});
});
JS

Результат:

3

В данном примере классы .hover и .active добавляются только к <tr>.

/* Hover */
.table .hover td:after {
	content: '';
	position: absolute;
	top: 0px;
	right: 0px;    
	bottom: 0px;    
	left: 0px;
	width: 105%;
	border-top: 3px solid #ffe5c5;
	border-bottom: 3px solid #ffe5c5;
}
.table .hover td:first-child:after {
	border-left: 3px solid #ffe5c5;
}
.table .hover td:last-child:after {
	border-right: 3px solid #ffe5c5;
	width: auto;
}

/* Click */
.table .active td:after {
	content: '';
	position: absolute;
	top: 0px;
	right: 0px;    
	bottom: 0px;    
	left: 0px;
	width: 105%;
	border-top: 3px solid orange;
	border-bottom: 3px solid orange;
}
.table .active td:first-child:after {
	border-left: 3px solid orange;
}
.table .active td:last-child:after {
	border-right: 3px solid orange;
	width: auto;
}
CSS
$(document).ready(function(){
	$('.table tr').hover(function(){
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});

	$('.table tr').click(function(){
		$('.table tr').removeClass('active');
		$(this).addClass('active');
	});
});
JS

Результат:

10.09.2019
15872

Комментарии 1

Eduard Proger Eduard Proger
26 июня 2020 в 14:30
Добрый день, отличный контент как всегда, ещё прикольно было бы, чтобы выделенная таблица или строка бы увеличивалась в размерах, думаю вы встречались с такой темой.

, чтобы добавить комментарий.

Другие публикации

Стилизация Checkbox
Несколько примеров как изменить внешний вид чекбоксов с помощью CSS, изображений и немного JS.
74115
+3
Фиксированное горизонтальное меню с активными пунктами
Пример горизонтального меню для лэндингов, в котором реализовано...
12591
+3
Отметить или снять все чекбоксы в таблице
Мини JQuery плагин позволяет отметить или снять одним кликом чекбоксы в таблицах и отметить чекбокс по клику на сроку...
11173
0
Сложение и форматирование цен в JS
Есть две переменные с форматированными ценами... Нужно их сложить. Сразу привести их числу с помощью parseInt() не...
5773
+2
Генерация счета на оплату PDF PHP
С помощью расширения dompdf можно легко сформировать PDF файл. По сути, dompdf - это конвертер HTML в PDF который...
65999
+33
Как сделать полосатую таблицу на HTML, CSS, JS, PHP
Сборник методов как сделать HTML таблицу «полосатой» или, как её еще называют «таблица с зеброй».
22924
-2