一旦选中复选框并将默认不透明度设置为 0.5(半不透明度),我想将复选框图像的不透明度更改为 1.0(正常不透明度)。但是我对 JavaScript 和 CSS 中的编码一无所知。
<input type="checkbox" id="n1" name="n1" style="display: none;" /><label for="n1"><img src="images/n1.png" width="20" height="20" /></label>
<input type="checkbox" id="n2" name="n2" style="display: none;" /><label for="n2"><img src="images/n2.png" width="20" height="20" /></label>
...
<input type="checkbox" id="n50" name="n50" style="display: none;" /><label for="n2"><img src="images/n50.png" width="20" height="20" /></label>
最佳答案
这是一种不用 JS,只用 CSS 的方法:
label img {
opacity : 0.5;
}
input[type=checkbox]:checked + label img {
opacity : 1;
}
请注意,它使用了 adjacent sibling selector +
, 因此它依赖于紧跟在相应复选框元素之后的标签元素。
但是如果你想支持没有实现 CSS :checked
selector 的 IE<=8我仍然建议定义上面的 label img
类来设置默认的不透明度,然后在选中时定义以下类:
label.checked img {
opacity : 1;
}
...然后使用 JS 添加和删除该类:
document.onclick = function(e) {
if (!e) e = window.event;
var el = e.target || e.srcElement;
if (el.type === "checkbox") {
if (el.checked)
el.nextSibling.className += " checked";
else
el.nextSibling.className = el.nextSibling.className.replace(/\bchecked\b/,"");
}
};
关于javascript - 将不透明度更改切换为复选框图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19888904/