刷新之后血量没问题,但是再点击就不动了
来源:2-3 存储实现打怪小案例
慕丝5957077
2020-03-12 15:47:36
localStorage变成了这样,不是直接更新值,而是不断地加在后面42.06405607251442514.8544442214292767.62084225436744143.349511855069398
<!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;
}
body{
width: 1200px;
height: 600px;
}
img {
cursor: pointer;
display: block;
position: absolute;
top: 300px;
left: 600px;
margin: -112px 0 0 -112px;
}
.line {
border: 4px black solid;
width: 300px;
height: 20px;
position: relative;
left: 50%;
top: 20px;
margin-left: -152px;
}
.line .score {
height: 100%;
width: 0px;
background-color: yellow;
}
</style>
</head>
<body>
<div class="line">
<div class="score"></div>
</div>
<img src="./money.jpg" alt="">
<script type="text/javascript">
var num = 0,
timer = null,
max=0;
var img=document.querySelector("img"),
scoreNode=document.querySelector(".score");
if(localStorage.score){
max=localStorage.score;
scoreNode.style.width=max+"px";
}
img.onclick = function () {
var score=Math.random()*20;
max+=score;
scoreNode.style.width=max+"px";
localStorage.setItem("score",max);
clearInterval(timer);
var timer = setInterval(function () {
num++;
if (num == 10) {
clearInterval(timer);
num=0;
img.style.left =600+"px";
img.style.top =300+"px";
return false;
}
img.style.left =Math.random()*-20+10+600+"px";
img.style.top =Math.random()*-20+10+300+"px";
},30)
}
</script>
</body>
</html>
1回答
同学你好,这是因为存储之后数据是字符串类型(无论存储的时候是什么类型),所以相加的时候值进行了拼接,而不是数字的相加。
建议:转化一下获取的值
自己再测试下,祝学习愉快!
相似问题