MENU

为站点添加每日一句的简单方法

2020 年 01 月 12 日 • 阅读: 19561 • 博客

2020 水文第二篇,为任意站点添加英文每日一句,随机从金山词霸、有道词典、欧路词典、海词词典和扇贝英语获取内容。你可在博客首页查看效果,大佬请跳过。

引入 JS

将以下代码加入到 <head> 标签中。对于本主题,依次进入 控制台 - 外观 - 设置外观 - 主题自定义扩展,将代码加入到 自定义 HTML 元素拓展 - 标签: head 头部 (meta 元素后),也可直接加入到主题对应的 header.php 中的 </head> 标签前。

<script>
    // 获取每日一句并显示
    document.addEventListener('DOMContentLoaded', initDescription);
    function initDescription() {
        // 锚点开始
        if (location.href !== location.origin + '/') return;
        const h1 = document.querySelector('h1.blog-title');
        const h2 = document.querySelector('h2.blog-description');
        // 锚点结束

        const local = {
            set: (key, value) => localStorage.setItem(key, JSON.stringify(value)),
            get: key => {
                const value = JSON.parse(localStorage.getItem(key));
                if (value && new Date(value.date).toDateString() !== new Date().toDateString()) return null;
                return value;
            }
        };
        const render = (data, save) => {
            h1.innerHTML = data.sentence, h2.innerHTML = data.translation;
            if (save) local.set('sentence', data);
        };
        const data = local.get('sentence');
        if (data) { render(data); return; }
        fetch('//logi.im/api/sentence/').then(response => response.json()).then(json => render(json, true));
    }
</script>

如果你开启了 PJAX,可能需要单独加入回调函数。对于本主题,依次进入 控制台 - 外观 - 设置外观 - PJAX(BETA) - PJAX RELOAD,将 initDescription(); 添加进入即可。

其他主题

其他主题需要通过 F12 找到对应锚点,替换代码中那三行,不知道怎么找的,留下 博客链接要加入的位置,我看到后会将锚点代码更新到此。

演示地址

if (location.href !== location.origin + '/index.php') return;
const h1 = document.querySelector('h1.site-name');
const h2 = document.querySelector('h2.site-description');

如果你想自行部署 API,回复后刷新页面即可获取 PHP 源码。

此处内容需要评论回复后方可阅读

TG 大佬群 QQ 大佬群

最后编辑于: 2020 年 02 月 10 日
返回文章列表 文章二维码
本页链接的二维码
打赏二维码
添加新评论

Loading captcha...

已有 32 条评论
  1. Dianr Dianr   Android 9  MIUI Browser 11.7.24

    来了

    1. LOGI LOGI   Windows 10 x64 Edition  Google Chrome 79.0.3945.130

      @Dianr欢迎

  2. QaQ QaQ   Windows 10 x64 Edition  Google Chrome 79.0.3945.117

    阿偶找不来::quyin:amazing::

    1. LOGI LOGI   Windows 10 x64 Edition  Google Chrome 79.0.3945.117

      @QaQ可以加群说一下想放在哪,我帮你找呀

  3. Toki Toki   Mac OS X 10.14  Firefox 73.0

    来啦来啦~ ::quyin:maimeng::

    1. LOGI LOGI   Windows 10 x64 Edition  Google Chrome 79.0.3945.117

      @Toki所以你的博客在哪@(捂嘴笑)

    2. Toki Toki   Mac OS X 10.14  Firefox 73.0

      @LOGI丢人就不放出来了。。。自己做笔记用~ 谢谢大佬解答 ::quyin:shakinghead::

  4. 帅人 帅人   Android 9  Android Webkit 4.0

    感谢大佬分享

  5. 子午 子午   Windows 10 x64 Edition  Google Chrome 79.0.3945.79

    @(你懂的)

  6. 妞妞 妞妞   iOS 12.1.4  Safari 12.0

    评论一下