存在的问题,再次刷新能止住血,但一点击又会回到满格,这是啥原因
来源:2-3 存储实现打怪小案例
慕函数4234673
2020-03-29 17:45:25
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
*,div{
margin: 0;
padding: 0;
}
body{
position: relative;
height: 100%;
}
html{height: 100%;}
.img{
width: 200px;
height: 200px;
position: absolute;
top:50%;
left:50%;
margin-top:-100px;
margin-left: -100px;
}
.box{
width: 400px;
height: 30px;
position: absolute;
top:10%;
left:50%;
margin-left: -200px;
border: 1px solid black;
}
.xue{
background: red;
width: 400px;
height: 100%;
transform: .7s;
border: 1px solid black;
}
</style>
</head>
<body>
<div class="box">
<div class="xue"></div>
</div>
<img src="1.jpeg" class="img">
</body>
<script type="text/javascript">
var xue=document.querySelector(".xue")
if(localStorage.x){
max=localStorage.x
xue.style.width=max+"px"
}
var timer=null,num=0,max=400
onclick=function(){
r=Math.random()*5+5
max-=r
localStorage.setItem("x",max)
//console.log(localStorage)
xue.style.width=max+"px"
clearInterval(timer)
timer=setInterval(function(){
num++
if(num==5){
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>
</html>
存在的问题,再次刷新能止住血,但一点击又会回到满格,这是啥原因
这里的num是不是只是为了判断的一个变量
1回答
好帮手慕糖
2020-03-29
同学你好,关于你的问题,回答如下:
1、是因为又重新声明了max导致的,建议:在判断前面声明。这样判断设置了之后,就不会再重新声明被替换了。

2、是的。
如果我的回答帮助了你,欢迎采纳,祝学习愉快~
相似问题