【问题标题】:I want some text to change color when the user checks a checkbox当用户选中复选框时,我希望一些文本改变颜色
【发布时间】:2013-02-20 08:13:47
【问题描述】:

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

这是我的代码:

<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 
   }
}

【问题讨论】:

  • 您似乎从未致电 hasTickedBox。您希望触发什么?
  • 对不起。我希望触发器是用户检查复选框。
  • 你试过什么?

标签: javascript


【解决方案1】:

您要找的房产是.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";
    }
}

【讨论】:

  • 除非你想改变&lt;p&gt;的颜色,而不是复选框。
  • 我将如何改变

    而不是 chkbx 的颜色?

  • 谢谢,伙计!所以现在,如果我把函数放在头部,把

    和复选框放在正文中,它应该可以工作吗?

  • 我会使用:onchange="hasTickedBox(this.checkBoxID)"
【解决方案2】:

假设你使用的是 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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2019-01-20
    • 2017-01-16
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多