Skip to content

使用SweetAlert+localStorage实现简易的今日人品

Cover 不多说,直接上源码。

WARNING

需要先引入SweetAlert库,否则无法运行

javascript
function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function setTodayLuck() {
        const now = new Date();
        const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
        const timeUntilTomorrow = tomorrow - now;

        let luckValue = localStorage.getItem('todayLuck');
        if (!luckValue) {
            luckValue = getRandomInt(1, 100);
            localStorage.setItem('todayLuck', luckValue);
            localStorage.setItem('expireTime', now.getTime() + timeUntilTomorrow);
        } else {
            const expireTime = Number(localStorage.getItem('expireTime'));
            if (now.getTime() > expireTime) {
                luckValue = getRandomInt(1, 100);
                localStorage.removeItem('todayLuck');
                localStorage.removeItem('expireTime');
                localStorage.setItem('todayLuck', luckValue);
                localStorage.setItem('expireTime', now.getTime() + timeUntilTomorrow);
            }
        }

        let displayValue;
        if (luckValue == 1) {
            displayValue = '1!那种事情不要啊...';
        } else if (luckValue >= 2 && luckValue <= 9) {
            displayValue = luckValue + '...(是百分制哦)';
        } else if (luckValue >= 10 && luckValue <= 39) {
            displayValue = luckValue + '!emmmm...';
        } else if (luckValue >= 40 && luckValue <= 60) {
            displayValue = luckValue + '!一般般啦!';
        } else if (luckValue >= 61 && luckValue <= 80) {
            displayValue = luckValue + '!不错哦!';
        } else if (luckValue >= 81 && luckValue <= 90) {
            displayValue = luckValue + '!好评如潮!';
        } else if (luckValue >= 91 && luckValue <= 99) {
            displayValue = luckValue + '!天上掉馅饼!';
        } else if (luckValue == 100) {
            displayValue = luckValue + '!神一般的存在!';
        }
        return displayValue;
    }

    function showTodayLuck() {
        const luckMessage = setTodayLuck();
        swal('今日人品', `你今天的人品值是:${luckMessage}`, 'info');
    }

或者你也可以引用本站的文件 https://file.verr.top/js/luckNumber.js

使用

你可以通过调用showTodayLuck函数来显示今日人品,例如:

html
<button onclick="showTodayLuck()">今日人品</button>
html
<a href="javascript:showTodayLuck()" target="_self">今日人品</a>

或者其他你喜欢的方式!

上次更新于: