该博客描述如果使用JavaScript实现随机生成星星并点击消失的小游戏。
效果:
代码:
html:因为是JavaScript动态生成小星星和点击消失,所以body里面不需要手动添加元素
css:
body {position: relative;background-color: black;}div {position: absolute;width: 50px;height: 50px;}div img {width: 100%;height: 100%;}
javascript:
function getRandom(min, max) {return Math.floor(Math.random() * (max - min + 1) + min);}window.addEventListener('load', function() {var creatstar = setInterval(function() {var div = document.createElement('div');var starWidth = getRandom(20, 100);var starHeight = starWidth;var starLeft = getRandom(0, window.innerWidth - starWidth - 50);var starTop = getRandom(0, window.innerHeight - starHeight - 50);div.style.top = starTop + 'px';div.style.left = starLeft + 'px';div.style.width = starWidth + 'px';div.style.height = starHeight + 'px';document.body.appendChild(div);var img = document.createElement('img');img.src = 'xingxing.gif';div.appendChild(img);}, 1000);document.addEventListener('click', function(e) {document.body.removeChild(e.target.parentNode);});});
星星素材: