一刷新,血就回满,但点击的话,存住的血好使,刷新存不住血,求助
来源:2-3 存储实现打怪小案例
慕粉1451226
2021-06-02 08:52:56
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
user-select: none;
}
body,html{
height: 100%;
}
body{
position: relative;
}
img{
position: absolute;
left: calc(50% - 128px);
top: calc(50% - 150px);
cursor: pointer;
}
.line{
width: 400px;
height: 20px;
border: 2px solid black;
position: absolute;
left: calc(50% - 200px);
top: 20px;
}
.xie{
width: 400px;
background-color: #f00;
height: 20px;
}
</style>
</head>
<body>
<div class="line">
<div class="xie"></div>
</div>
<img src="./fuwo.jpg" class="guai">
<script>
var guai = document.querySelector(".guai");
var timer = null,
num = 0;
onclick = function(){
var r = Math.random() * 5 + 5,
max = 400,
xieNode = document.querySelector(".xie");
if (localStorage.x) {
max = localStorage.x;
xieNode.style.width = max + "px";
if (localStorage.x <= 0) {
localStorage.x = 400
max = localStorage.x;
xieNode.style.width = max + "px";
}
}
max = max - r;
// console.log(max);
xieNode.style.width = max + "px";
localStorage.setItem("x",max);
clearInterval(timer)
timer = setInterval(function () {
num++;
if(num == 10){
clearInterval(timer);
num = 0;
document.body.style.top = 0;
document.body.style.left = 0;
return;
}
})
document.body.style.top = Math.random() * -20 + 10 + 'px';
document.body.style.left = Math.random() * -20 + 10 + 'px';
}
</script>
</body>
</html>
1回答
好帮手慕慕子
2021-06-02
同学你好,因为从缓存中获取值设置血条宽度的代码写在了点击事件中,导致只有在点击时才会执行这段代码,刷新页面的时候并不会点击事件获取存储的血条值,所以无法实现效果。
建议:在点击事件外设置max值,获取血条元素,从缓存中获取值设置血条宽度。如下:
祝学习愉快~
相似问题