一刷新,血就回满,但点击的话,存住的血好使,刷新存不住血,求助

来源: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>

        *{

            margin0;

            padding0;

            user-selectnone;

        }

        body,html{

            height100%;

        }

        body{

            positionrelative;

        }

        img{

            positionabsolute;

            leftcalc(50% - 128px);

            topcalc(50% - 150px);

            cursorpointer;

        }

        .line{

            width400px;

            height20px;

            border2px solid black;

            positionabsolute;

            leftcalc(50% - 200px);

            top20px;

        }

        .xie{

            width400px;

            background-color#f00;

            height20px;

        }

    </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值,获取血条元素,从缓存中获取值设置血条宽度。如下:

http://img.mukewang.com/climg/60b6ee1f091cd00107570784.jpg

祝学习愉快~

0

0 学习 · 6815 问题

查看课程