DOM案例
1.开关灯效果
<!DOCTYPE html>
<html lang="en">
<head>
<mate charset="UTF-8">
<title>
开/关灯效果
</title>
<style>
.cls{
background-color: black;
}
</style>
</head>
<body id="bd">
<input type="button" value="开/关灯" id="btn1">
<script>
//获取元素id
//注册事件
//添加事件函数
document.getElementById("btn1").onclick=function(){
// document.getElementById("bd").style.backgroundColor="black";
//三元表达式
document.getElementById("bd").className=document.getElementById("bd").className!="cls"?"cls":"";
};
</script>
</body>
</html>
2.排他
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>排他</title>
<!-- 引用外部js -->
<script type="text/javascript" src="../base.js"></script>
</head>
<body>
<input type="button" value="没怀孕">
<input type="button" value="没怀孕">
<input type="button" value="没怀孕">
<input type="button" value="没怀孕">
<input type="button" value="没怀孕">
<input type="button" value="没怀孕">
<input type="button" value="没怀孕">
<input type="button" value="没怀孕">
<input type="button" value="没怀孕">
<script>
//获取所有的按钮,分别注册点击事件
var btnObjs=document.getElementsByTagName("input");
//遍历按钮,点击谁,谁就怀孕
for(i=0;i<btnObjs.length;i++){
btnObjs[i].onclick=function(){
for(j=0;j<btnObjs.length;j++){
//遍历按钮,设定初始值
btnObjs[j].value="没怀孕";
}
this.value="怀孕了";
};
}
</script>
</body>
</html>
原文:https://www.cnblogs.com/hanks-mimi/p/12635043.html