我已经创建了一个模仿复选框输入的按钮,并在点击时编写了一些js代码:
以下是代码:
$
这是HTML代码:
function taskDone(nodelistindex) {
thisElement = document.getElementsByClassName('tb_checkbutton')[nodelistindex];
readStyle = getComputedStyle(thisElement);
vvalue = readStyle.getPropertyValue('--checked');
console.log(vvalue + " (before)");
if (readStyle.getPropertyValue("--checked") == 0) {
console.log(vvalue + " in if");
// thisElement.style.setProperty("--checked",1);
thisElement.style = "background-color:green;";
thisElement.style.setProperty("--checked",1);
} else {
console.log(vvalue + " in else");
thisElement.style.setProperty("--checked",0);
thisElement.style = "background-color:var(--tcolorvalue);";
}
console.log(vvalue+" (after)");
}
以上代码为我提出了这些问题:
<button style="--tcolorvalue:#CBCBCB; --checked:0" class="tb_checkbutton" onclick="taskDone(0)">
0 (before)
0 in if
0 (after)
1 (before)
1 in else
1 (after)
0 (before)
0 in if
0 (after)
为什么?
感觉CSS变量几乎完全被我破坏了,我一直试图解决问题,每次编辑它时,都会给我带来更多问题。如何修改代码以使其稳定?
这是我期待的控制台日志:
0 (before)
0 in if
0 (after)
(before)
in else
(after)
(before)
in if
(after)