飞舞的泡泡球
效果图如下
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title><style>.container{width: 800px;height: 800px;background-color: #eee;margin: 60px auto;box-shadow: 5px 8px 2px #bdbdbd inset;border: 1px solid #666;position: relative;}.but{margin: 0px auto;width: 800px;}.ball{border-radius: 50%;/*background-color: rgb(157 110 233);*/position: absolute;}</style></head><body><div class="container" id="cont"></div><div class="but"><button id="btn" onclick="pball()">弹球</button></div><script>var comobj=document.getElementById('cont');function pball(){var myWidth = Math.floor(Math.random()*30+10);var speY = Math.floor(Math.random()*10-6);var speX = Math.floor(Math.random()*10-6);var myball=document.createElement("div");var mycolorR = Math.floor(Math.random()*255);var mycolorB = Math.floor(Math.random()*255);var mycolorG = Math.floor(Math.random()*255);var contW = comobj.clientWidth;var contH = comobj.clientHeight;// console.log(mycolorR+','+mycolorG)myball.style.backgroundColor = `rgb(${mycolorR} ${mycolorB} ${mycolorG})`;myball.style.width = `${myWidth}px`;myball.style.height = `${myWidth}px`;// console.log(`rgb(${mycolorR} ${mycolorB} ${mycolorG})`);myball.className='ball';comobj.appendChild(myball);myball.style.top = `${contW/2}px`;myball.style.left =`${contH/2}px`;// console.log( `${comobj.clientWidth/2}px`)setInterval(function () {var oftop = myball.offsetTop;var ofleft= myball.offsetLeft;var myWid = myball.offsetWidth;var myhei = myball.offsetHeight;var tp= contH-myhei;var lp = contW-myWid;var opSy = 0;var lpSx = 0;opSy = oftop + speY;lpSx = ofleft + speX;if (opSy<=0){myball.style.top='0px';speY = ~speY;} else if (opSy>=tp) {myball.style.top = `${tp}px`;speY = ~speY;}else {myball.style.top = `${opSy}px`;}if (lpSx<=0){myball.style.left='0px';speX = ~speX;}else if (lpSx>=lp) {myball.style.left = `${lp}px`;speX = ~speX;}else {myball.style.left = `${lpSx}px`;}},50)}</script></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号