<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>闪烁星星</title> <style type="text/css"> *{ margin: 0; padding: 0; } .main{ margin: 0 auto; width: 100%; height: 700px; position: relative; background-color: #333; } .main span{ background: url(../img/shanshuoxingxing/star.png); width: 16px; height: 21px; position: absolute; left: 0; top: 0; } </style> </head> <body> <div class="main"> </div> </body> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script> <script> $(function(){ var len=100 //设定星星的个数 for(var i=0;i<len;i++){ var x=Math.floor(Math.random()*$('.main').innerWidth())+'px' var y=Math.random()*$('.main').innerHeight()+'px' $('.main').append("<span style='left:"+x+";top:"+y+"'></span>") hide() // show() } function hide(){ $('.main span').animate({opacity:0},100,function(){ show() }) } function show(){ $('.main span').animate({opacity:1},50,function(){ hide() }) } }) </script> </html>