老师看一下
来源:2-3 存储实现打怪小案例
qq_慕瓜7049344
2020-08-19 10:48:12
<!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 {
position: relative;
overflow: hidden;
}
.line {
width: 400px;
height: 20px;
border: 2px solid #cccccc;
position: absolute;
left: 50%;
top: 60px;
margin-left: -170px;
}
.xie {
width: 400px;
height: 100%;
background-color: red;
}
.guai {
width: 290px;
height: 270px;
position: absolute;
left: 50%;
top: 130px;
margin-left: -145px;
}
</style>
</head>
<body>
<div class="line">
<div class="xie"></div>
</div>
<div class="guai"><img src="01.jpg" alt=""></div>
<script>
var xieNode = document.querySelector('.xie');
var imgNode = document.querySelector('img'),
max = 400;
if(localStorage.xie){
max = localStorage.xie;
xieNode.style.width = max + 'px';
};
imgNode.onclick = function () {
if(max<=0){
localStorage.setItem('xie',400);
xieNode.style.width = 0+'px';
return;
}
var num = 0,
time = null,
r = Math.random() * 5 + 5;
max -= r;
console.log(max);
clearInterval(time);
localStorage.setItem('xie',max);
console.log(localStorage);
time = setInterval(function () { //每0.3秒执行一次
num++;
if (num == 5) { //当num=5的时候停止并且清除
clearInterval(time);
document.body.style.left = 0 + 'px';
document.body.style.top = 0 + 'px';
return;
}
//设置抖动
document.body.style.left = Math.random() * -20 + 10 + 'px';
document.body.style.top = Math.random() * -20 + 10 + 'px';
}, 30)
}
xieNode.style.width = max + 'px';
console.log(max);
</script>
</body>
</html>
为什么我那个宽度不能放在最底下 然后前面使用它的max值变成nan
2回答
好帮手慕星星
2020-08-19
同学你好,直接将宽度变为0是可以的。因为每次减少的宽度是随机出来的,不能保证最后一次点击的时候和剩余的宽度相等,所以可以这样限制。
祝学习愉快!
好帮手慕星星
2020-08-19
同学你好,宽度设置不能放在最下面(点击事件外面),否则只会执行一次,是尝试max的值。但是可以放在点击事件里面的最下面,点击一次,执行一次
自己测试下,祝学习愉快!
相似问题