getElementById 学习
2017-09-07 14:11 陆陆陆小芳 阅读(641) 评论(0) 编辑 收藏 举报document.getElementById(" ") 得到的是一个对象,根据指定的 id 属性值得到对象
以下的例子:获得的id 为chkAll的对象。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function checkAll() {
var chkAll = document.getElementById("chkAll");
var chks = document.getElementsByClassName("chobby");
var chksLenght = chks.length;
var isChkAllChecked = chkAll.checked;
var id = "font1";
var h1_id_font1_ = document.getElementById(id);
var h1_style = h1_id_font1_.style;
chks[i].checked = isChkAllChecked;
}
//
var cf = document.getElementById("cf");
var cfIsChecked = cf.checked;
if(cfIsChecked)
{
h1_style.background="red";
}
else{h1_style.background="yellow";}
}
// h1设置了aaaaaa的背景颜色为yellow,当点击全选后就变为red
function reverseCheck() {
var chks = document.getElementsByName("hobby");
for (var i = 0; i < chks.length; i++) {
chks[i].checked = !chks[i].checked;
}
}
function checkSingle() {
var b = true; //假设全被选中
var chkAll = document.getElementById("chkAll");
var chks = document.getElementsByName("hobby");
for (var i = 0; i < chks.length; i++) {
//查找所有子的checkbox,判断是否被选中
//如果有一个checkbox没有被选中,则会退出循环,最终圈被选中checkbox为false
if (!chks[i].checked) {
b = false;
break;
}
}
chkAll.checked = b;
}
</script>
</head>
<body>
<h1 id="font1" style="background: yellow">aaaaaa</h1>
<input id="cf" class="chobby" type="checkbox" value="cf" name="hobby"/>吃饭<br/>
<input class="chobby" type="checkbox" value="sj" name="hobby"/>睡觉<br/>
<input class="chobby" type="checkbox" value="ddd" name="hobby"/>打豆豆<br/>
<br/> <br/>
<input id="chkAll" type="checkbox" style="background: azure" value="quanxuanle" onclick="checkAll();"/>全选
<input type="button" value="反选" onclick="reverseCheck();"/>
<input type="button" value="按钮" onclick="btnClick();"/>
<br/>
<input type="checkbox" value="ctl"/>春天里<br/>
<input type="checkbox" value="xtl"/>夏天里<br/>
</body>
</html>