我有一个基本功能,即更改表格中的单元格颜色。
我从Slider获取值并尝试为表格中的单元格着色,就好像它们正在跟踪滑块一样。它只有一半工作但跟不上滑块或太快了。
对我而言,似乎myFunction()在滑块的每一步执行多次,而它只应在滑块值更改时触发...
以下是代码:
var p =0;
function myFunction()
{
var SliderValue = $('#slider-step').val();
var k = Math.floor(SliderValue/10);
if (p == k) {
$('.grid').find('tr:first td:nth-child(' + k + ')').css("background-color", "#F0B4F8");
console.log("SliderValue--->" + SliderValue + " k = " + k + " p = " + p);
p = 0;
}
else {
$('.grid').find('tr:first td:nth-child(' + k + ')').css("background-color", "#FFFFFF");
console.log("SliderValue--->" + SliderValue + " k = " + k + " p = " + p);
p = k;
}
}
CSS:
#grid, #grid td {
border: 1px solid black;
background-color: yellow;
}
#grid td {
width: 25px;
height: 10px;
}
#grid td, th {
border-left: solid 3px black;
}
HTML:表格:
<table class="grid" id="grid" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</tbody>
</table>
HTML:Slider:
<label for="slider-step">
Position
</label>
<input type="range" name="slider-step" id="slider-step" value="0" min="0"
max="100" step="6.4" class="ui-hidden-accessible" onchange="myFunction()">
答案 0 :(得分:1)
也许这会让你走上正轨。 Fiddle
滑块步骤的第一个通知是10
,以便在代码中将除法与10匹配。然后我将其更改为使用p
来存储滑块的最后一个值。这允许与当前值进行比较,并且可以在向上或向下滑动时适当地着色。
var p =0;
function myFunction()
{
var SliderValue = $('#slider-step').val();
var k = Math.floor(SliderValue/10);
// if the value is decreasing
if (p >= k) {
$('.grid').find('tr:first td:nth-child(' + k + ')').css("background-color", "#F0B4F8");
console.log("SliderValue--->" + SliderValue + " k = " + k + " p = " + p);
// otherwise it's increasing
} else {
$('.grid').find('tr:first td:nth-child(' + k + ')').css("background-color", "#FFFFFF");
console.log("SliderValue--->" + SliderValue + " k = " + k + " p = " + p);
}
// save value for comparison next time
p = k;
}