复制代码:

<body>
    <div id="hitokotoDisplay">
        <div id="hitokotoText">加载中...</div>
        <div id="fromWrapper">
            —— <span id="fromSource"></span> <span id="fromWho"></span>
        </div>
    </div>
    <script>
        (function() {
            "use strict";
            const hitokotoText = document.getElementById('hitokotoText');
            const fromSource = document.getElementById('fromSource');
            const fromWho = document.getElementById('fromWho');
            const DEFAULT_DATA = {
                hitokoto: "0。",
                from: "0",
                from_who: "0"
            };
            let timer = null;
            function displayHitokoto(data) {
                if (!data || typeof data !== 'object') {
                    data = DEFAULT_DATA;
                }
                const text = data.hitokoto || DEFAULT_DATA.hitokoto;
                const from = data.from || DEFAULT_DATA.from;
                const who = data.from_who || DEFAULT_DATA.from_who;

                hitokotoText.textContent = text;
                fromSource.textContent = from;
                fromWho.textContent = who;
            }
            function showLoading() {
                hitokotoText.textContent = '加载中...';
                fromSource.textContent = '';
                fromWho.textContent = '';
            }
            async function fetchHitokoto() {
                showLoading();
                try {
                    const response = await fetch('https://v1.hitokoto.cn/', {
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json'
                        }
                    });

                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}`);
                    }
                    const data = await response.json();

                    if (!data || typeof data.hitokoto !== 'string' || data.hitokoto.trim() === '') {
                        throw new Error('数据格式异常');
                    }
                    displayHitokoto(data);

                } catch (error) {
                    console.warn('一言获取失败:', error);
                    displayHitokoto(DEFAULT_DATA);
                }
            }
            fetchHitokoto();
            timer = setInterval(fetchHitokoto, 5000);
window.addEventListener('beforeunload', function() {
                if (timer) {
                    clearInterval(timer);
                    timer = null;
                }
            });
        })();
    </script>
</body>
</html>

0 条评论

目前还没有评论...