案例一:目的:通过按钮实现全选、全不选、反选等功能。
思路:第一步:根据标签数设置input标签,根据按钮数设置bottom标签进行布局;第二步:Js 需要判断每一个input标签是否为真值,全选的时候为真值,全不选的时候为假值,反选的时候需要用到if判断,如果为真则为空,否则为假,采用下角标的方式,inpt[i]的方式 来判断,检查checked的值。
代码如下:
<body> <p> 请选择你要学的课程</p> <input type="checkbox"/>HTML <input type="checkbox"/>CSS <input type="checkbox"/>Javascript <input type="checkbox"/>JQuery <input type="checkbox"/>PHP <input type="checkbox"/>C语言 <input type="checkbox"/>Python <button id="btn1">全选</button> <button id="btn2">全不选</button> <button id="btn3">反选</button> <script type="text/javascript"> var btn1=document.getElementById("btn1"); var btn2=document.getElementById("btn2"); var btn3=document.getElementById("btn3"); var inpt=document.getElementsByTagName("input"); btn1.onclick=function(){ for(var i=0;i<=inpt.length-1;i++){ inpt[i].checked=true; }; }; btn2.onclick=function(){ for(var i=0;i<=inpt.length-1;i++){ inpt[i].checked=false; }; }; btn3.onclick=function(){ for(var i=0;i<=inpt.length-1;i++){ if(inpt[i].checked===false){ inpt[i].checked=true; } else{ inpt[i].checked=false; }; }; }; </script> </body> |
效果如下:
点击反选后:
案例二:目的:通过按钮实现样式变宽变高变背景等功能。
注意事项:在Js原生的代码中backgroundColor的写法,应该用驼峰命名法,后面的值例如red应该加上引号写成"red",否则不能显示。
<body> <button id="btn1">变高</button> <button id="btn2">变宽</button> <button id="btn3">变背景</button> <button id="btn4">变字体大小</button> <button id="btn5">还原</button> <div id="div1">Hello World </div> <script> div1=document.getElementById('div1'); btn1=document.getElementById('btn1'); btn2=document.getElementById('btn2'); btn3=document.getElementById('btn3'); btn4=document.getElementById('btn4'); btn5=document.getElementById('btn5'); btn1.onclick=function(){ div1.style.height='200px'; }; btn2.onclick=function(){ div1.style.width='200px'; }; btn3.onclick=function(){ div1.style.backgroundColor="blue"; }; btn4.onclick=function(){ div1.style.fontSize='50px'; }; btn5.onclick=function(){ div1.style.height= "100px"; div1.style.width="100px"; div1.style.backgroundColor= "red"; div1.style.color= "greenyellow"; div1.style.fontSize= "20px"; }; </script> </body> |
效果如下:
除还原按钮以外依次点击后效果