我希望一些文本在用户选中复选框时更改颜色

I want some text to change color when the user checks a checkbox

本文关键字:复选框 颜色 文本 用户 我希望      更新时间:2023-09-26

当用户勾选某些文本旁边的复选框时,我希望文本更改颜色。

这是我的代码:

<p style="color: #FF0000; font-weight: bold;">
   I have read and agree to the terms and conditions
   <input type="checkbox" id="termsChkbx" />
</p>

这是我迄今为止的功能:

function hasTickedBox( checkBoxID) {
   var chkbx = document.getElementById( checkBoxID );
   if ( chkbx.checked ) {
      //change the font color 
   } else {
      //do nothing 
   }
}

您要查找的属性是.style.color

更新的代码

<p id="termsP" style="color: #FF0000; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" /></p>

function hasTickedBox( checkBoxID) {
    var chkbx = document.getElementById( checkBoxID );
    if ( chkbx.checked ) {
        document.getElementById('termsP').style.color = "#000000";
    }
}

假设您使用的是jquery,您可以执行类似的操作

if(chkbx.checked) {
    $(chkbx).parent().css('color', 'new-color');
else {
   $(chkbx).parent().css('color', 'old-color');
} 

如果你不使用jquery,它会像一样

chxbx.parentNode.style.color = "new-color";

强制性小提琴:http://jsfiddle.net/Tv5ta/