You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为YOURLS的SLEEKY插件升级以适配新版Unsplash背景API

问题修复方案

你的代码核心问题是设置背景图的语句存在字符串拼接错误——你直接把data["results"][0]["urls"]["regular"]写在了字符串里,没有实际读取API返回的图片URL值,浏览器会把这段文本当作无效的图片路径,导致背景加载失败。

修复步骤及优化代码

1. 正确读取API返回的图片URL

使用模板字符串(ES6语法,兼容性良好)将实际的图片URL插入到url()中,而不是把取值代码写死在字符串里。

2. 增加异常判断

防止API返回结果为空时出现undefined报错,提升代码健壮性。

修复后的完整代码

<script type="text/javascript">
fetch("https://api.unsplash.com/search/photos?query=landscape&client_id=Uy5IEeK_PUDpPksrzxKLZeA3LCN2t3gXjP9ruCiQZfk")
    .then(response => {
        if (response.status !== 200) {
            console.log("请求出错,状态码: " + response.status);
            return;
        }
        return response.json();
    })
    .then(data => {
        // 先检查是否有有效返回结果
        if (data.results && data.results.length > 0) {
            const imgUrl = data.results[0].urls.regular;
            document.body.style.backgroundImage = `url(${imgUrl})`;
            // 补充背景样式,还原原主题的显示效果
            document.body.style.backgroundSize = "cover";
            document.body.style.backgroundPosition = "center center";
            document.body.style.backgroundRepeat = "no-repeat";
        } else {
            console.log("未获取到符合条件的图片");
        }
    })
    .catch(err => {
        console.log("请求失败: ", err);
    });
</script>

额外提示

  • 如果你是在YOURLS的Sleeky主题中添加这段代码,建议放在主题目录下的footer.php文件末尾,确保DOM完全加载后再执行脚本。
  • 注意Unsplash API存在调用次数配额限制,如果是公开访问的站点,需要留意配额使用情况,避免超出限制导致API失效。

内容的提问来源于stack exchange,提问作者clkd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:50:25