点击按钮,自动生成100个li,红、黄、蓝、绿四种颜色的顺序显示出现在页面中
CSS:
*{padding: 0;margin: 0;} ul,li{list-style: none;} #ul1{position: relative;} #ul1 li{ width: 48px; height: 48px; border: 1px solid #ccc; float: left; margin-right: 10px; margin-top: 10px; text-align: center; line-height: 40px; background: yellow; font-size: 30px; }
HTML:
<input id="btn1" type="button" value="自动生成100个Li"> <div> <ul id="ul1"></ul> </div>
JS:
<script type="text/javascript"> var oBtn=document.getElementById(‘btn1‘); var oUl=document.getElementById(‘ul1‘); var aLi=oUl.getElementsByTagName(‘li‘); var str=‘‘; var onOff=true;//切换开关 var arr=[‘red‘,‘yellow‘,‘blue‘,‘green‘]; oBtn.onclick=function(){ if (onOff) { for (var i = 0; i < 100; i++) { str+=‘<li>‘+i+‘</li>‘; }; }; oUl.innerHTML=str; onOff=false;//只能在一次点击按钮的时候添加内容 for (var i = 0; i < aLi.length; i++) { var n=i%arr.length;//取模获得0,1,2,3数字循环出现 aLi[i].style.background=arr[n]; }; } </script>
时间: 2024-10-13 00:48:59