<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>margin 传递</title> <style> ul,li{padding:0;margin:0;} #box{background:red;width:420px;height:100px;border:5px solid green;} ul {width:410px;height:70px;position:relative;list-style:none;margin:0 auto; display:inline-block;background:#ff00ff;;} ul li{display:inline-block;background:blue;width:30px;height:30px;text-align:center; line-height:30px;position:absolute;} </style> <script> window.onload=function(){ alert(4%4); var ul=document.getElementsByTagName(‘ul‘); var bTn=document.getElementById(‘btn1‘); arr=[‘red‘,‘yellow‘,‘blue‘,‘green‘]; var str=‘‘; for(var i=0;i<10;i++){ str+=‘<li>‘+(i+1)+‘</li>‘; } bTn.onclick=function(){ ul[0].innerHTML=str; var lis=ul[0].getElementsByTagName(‘li‘); for(var i=0;i<lis.length;i++){ lis[i].style.left=i*(30+5)+‘px‘; lis[i].style.background=arr[i%4]; } } } </script> </head> <body> <div id="box"> <input type="button" value="自动生成十个li" id="btn1" /> <ul></ul> </div> </body> </html> 第二种方法: <!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> <style> div{ width:50px; height:50px; border:1px solid #000000; position:absolute; left:0px; top:40px; font-size:40px; line-height:50px; text-align:center; font-weight:bold; } </style> <script> window.onload=function(){ var oBtn1=document.getElementById(‘btn1‘); var num=10; var str=‘‘; var arr=[‘red‘,‘yellow‘,‘blue‘,‘green‘]; for(var i=0;i<num;i++){ str=str+‘<div>‘+(i+1)+‘</div>‘; } oBtn1.onclick=function(){ document.body.innerHTML+=str; var aDv=document.getElementsByTagName(‘div‘); for(var s=0;s<num;s++){ aDv[s].style.left=s*(10+50)+‘px‘; aDv[s].style.backgroundColor=arr[s%4]; } } } </script> </head> <body> <input id="btn1" type="button" value="自动生成10个小方块" /> </body> </html>
时间: 2024-10-07 05:20:29