日期:2014-05-16  浏览次数:20316 次

checkbox 点击勾选和变色问题
checkbox 后面有文字。 需要点击文字就checkbox就勾选且文字背景变色,再次点击取消勾选,文字变色也取消

有一些checkbox 初始情况就是勾选的,怎么初始化它后面文字的背景。

我写的只能实现点击文字勾选checkbox ,初始化文字背景,和点击变背景都没有实现。

求高手指导

HTML code
<input type=checkbox name=ztid[] id='check2' value='2'><label for='check2'>高考</label>&nbsp;<br><input type=checkbox name=ztid[] id='check3' value='3'><label for='check3'>作文</label>&nbsp;<br><input type=checkbox name=ztid[] id='check30' value='30'><label for='check30'>零分作文</label>&nbsp;<br><input type=checkbox name=ztid[] id='check31' value='31' checked><label for='check31'>满分作文</label>




------解决方案--------------------
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
window.onload = function() {
    var oLabels = document.getElementsByTagName('label');
    for (var i = 0; i < oLabels.length; i ++) {
        if (document.getElementById(oLabels[i].getAttribute('for')).checked) oLabels[i].style.backgroundColor = '#FF0'; //初始化label背景色
        oLabels[i].onclick = function() {
            var chkbox = document.getElementById(this.getAttribute('for'));
            if (chkbox.checked) this.style.backgroundColor = '#FFF';
            else this.style.backgroundColor = '#FF0';
        }
    }
    var o = document.getElementsByName('ztid[]');
    for (var i = 0; i < o.length; i ++) {
        o[i].onclick = function() {
            var oNext = this.nextSibling;
            while (oNext.nodeType != 1) oNext = oNext.nextSibling;
            if (this.checked) oNext.style.backgroundColor = '#FF0';
            else oNext.style.backgroundColor = '#FFF';
        }
    }
}
</script>
</head>

<body>
<input type=checkbox name=ztid[] id='check2' value='2'>
<label for='check2'>高考</label>
&nbsp;<br>
<input type=checkbox name=ztid[] id='check3' value='3'>
<label for='check3'>作文</label>
&nbsp;<br>
<input type=checkbox name=ztid[] id='check30' value='30'>
<label for='check30'>零分作文</label>
&nbsp;<br>
<input type=checkbox name=ztid[] id='check31' value='31' checked>
<label for='check31'>满分作文</label>
</body>
</html>