JavaScript实现点击画面震动血条掉血的简易游戏效果


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>game</title>
    <style type="text/css">
    *{
        margin: 0;
        padding: 0;
        list-style: none;
    }
    html,body{
        height: 100%;
    }
    body{
        position: relative;
    }
    img{
        width: 300px;
        height: 300px;
    }
    .guai{
        position: absolute;
        left: 50%;
        top: 50%;
        margin: -150px 0 0 -150px;
    }
    .line{
        width: 400px;
        height: 20px;
        border: 4px solid black;
        position: absolute;
        left: 50%;
        top: 20px;
        margin:0 0 0 -204px;
    }
    .xie{
        width: 400px;
        height: 100%; 
        transition:.3s;
        background-color: red;
    }
    </style>
</head>
<body>
    <div class='line'>
		<div class='xie'></div>
	</div>
	<img src="https://vignette.wikia.nocookie.net/slimerancher/images/d/d1/%E7%B2%89%E7%BA%A2%E5%8F%B2%E8%8E%B1%E5%A7%86.png/revision/latest/scale-to-width-down/340?cb=20171002031904&path-prefix=zh" class='guai'>
    <script type="text/javascript">

    var num = 0,timer = null,max = 400,
		xieNode = document.querySelector('.xie');

		if(localStorage.x){          //从localStorage中取出上次血量
			max = localStorage.x;
			xieNode.style.width = max + 'px';
		};


		onclick = function(){
			var r = Math.random() * 5 + 5;
			max -= r;

			localStorage.setItem('x',max); //将血量存到localStorage中
			console.log(localStorage)
			xieNode.style.width = max + 'px';


			clearInterval(timer);  //实现画面震动效果
			timer = setInterval(function(){
				num++;             //num控制画面震动时间,点击一下后,每隔30ms震动一次,震动10次
				if(num == 10){
					clearInterval(timer);
					num = 0;
					document.body.style.left = 0;
					document.body.style.top = 0;
					return;
				};
				document.body.style.left = Math.random() * -20 + 10 + 'px';
				document.body.style.top = Math.random() * -20 + 10 + 'px';
			},30)
		}



    </script>
</body>
</html>

Reference:

https://class.imooc.com/lesson/811#mid=23003


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM