带有复选框的Javascript颜色更改

Javascript change of color with checkbox

本文关键字:颜色 Javascript 复选框      更新时间:2023-09-26

我这里有一个javascript,它可以在选中复选框时更改颜色,但它必须依靠使用外部库才能工作。它有可能不使用函数()之类的外部库吗?

<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
            <input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>

JS:

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
$(document).ready(function(){
    $('#termsChkbx').change(function(){
        if($(this).is(':checked'))
        {
            $(this).parent('p').css('color','black');
        }
        else
        {
             $(this).parent('p').css('color','red');
        }
    });  

您可以使用:

function isChecked(elem) {
    elem.parentNode.style.color = (elem.checked) ? 'black' : 'red';
}

jsFiddle示例

是的,这可以在不需要库的情况下完成。一个相当直接的翻译是:

document.addEventListener("DOMContentLoaded", function() {
    document.getElementById('termsChkbx').addEventListener("change", function(){
        if(this.checked) {
           this.parentNode.style.color = "black";
        } else {
           this.parentNode.style.color = "red";
        }
    }, false);
});

或者像这样短一点:

document.addEventListener("DOMContentLoaded", function() {
    document.getElementById('termsChkbx').addEventListener("change", function(){
      this.parentNode.style.color = this.checked ? "black" : "red";
    }, false);
});
<input type="checkbox" id="termsChkbx" onchange="termsChecked()"/>

并编写一个简单的JS函数:

function termsChecked() {
    var chk = document.getElementById('termsChkbx');
    if (chk.checked) {
         chk.parentNode.style.color = 'black';
    } else {
         chk.parentNode.style.color = 'red';
    }
}

这确实将JS代码放入HTML标记中,这并不是真正可取的,但这将适用于不支持DOMContentLoaded事件的旧浏览器。如果您只针对现代浏览器,那么ActionListener就是您的选择。

try,

function isChecked(){
  var chk = document.getElementById("termsChkbx");
  if(chk.checked){
     chk.parentElement.style.color  = "black";
  }
  else{
     chk.parentElement.style.color  = "red";
  }
}
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
            <input type="checkbox" id="termsChkbx" onchange="isChecked()"/></p>

纯javascript:

document.getElementById('termsChkbx').onclick = function() {
    document.getElementById('termsChkbx').parentElement.style.color = this.checked ? "black" : "red";
};

试试这个:

    $(document).ready(function(){
        $('#termsChkbx').on('change', function(e){
          e.preventDefault();
            if($(this).is(':checked'))
            {
                $(this).parent().css('color','black');
            }
            else
            {
                 $(this).parent().css('color','red');
            }
        });  
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div>
    <p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
    <input type="checkbox" id="termsChkbx" /></p>
</div>