首页 > 解决方案 > 如何加深html表格中重叠单元格的颜色

问题描述

我有 html 表格,我想加深重叠单元格的颜色。

例如,当我单击 cell 时2.nextAll(':lt(5)')方法更改类下一个4单元格。

在此处输入图像描述

然后当我单击3单元格时,颜色会改变。我想要的结果如下所示。重叠单元格的颜色将按照以下公式更改。

background-color: hsl(60,100%,95%);→<code>背景色:hsl(60,100%,90%);

在此处输入图像描述

有什么方法可以实现吗?

谢谢。

$(function() {
  $("td").click(function() {
    $(this).nextAll(':lt(4)').addClass('color');
  });
});
table td {
  width: 20px;
  overflow: hidden;
  display: inline-block;
  white-space: nowrap;
  border: 1px solid gray;
  text-align: center;
  padding: 5px;
  cursor: pointer;
}
.color {
  background-color: hsl(60,100%,95%);
}
.color2 {
  background-color: hsl(60,100%,90%);
}
.color3 {
  background-color: hsl(60,100%,85%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>

标签: javascriptjqueryhtmlcss

解决方案


您可以将.each()函数链接到.nextAll()结果,然后用于.hasClass()单独确定每个单元格应使用哪种颜色。

$(function() {
  $("td").click(function() {
    $(this).nextAll(':lt(4)').each(function(i) {
		if ($(this).hasClass("color2")) {
			$(this).addClass('color3');
		}
		else if ($(this).hasClass("color")) {
			$(this).addClass('color2');
		}
		else {
			$(this).addClass('color');
		}
		
		console.log(i);
	});
  });
});
table td {
  width: 20px;
  overflow: hidden;
  display: inline-block;
  white-space: nowrap;
  border: 1px solid gray;
  text-align: center;
  padding: 5px;
  cursor: pointer;
}
.color {
  background-color: hsl(60,100%,95%);
}
.color2 {
  background-color: hsl(60,100%,90%);
}
.color3 {
  background-color: hsl(60,100%,85%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>

它可能需要一些调整来删除不需要的类,但我测试过并且似乎可以正常工作。


推荐阅读