如何使用纯JS修改Blogger现有脚本限制文章标题不超过70字符
解决方案
原有代码问题
- 截断结果未赋值:
substring方法不会修改原字符串,仅返回截断后的新字符串,原有代码没有将返回值赋值给postTitle,截断逻辑完全不生效 - 方法名拼写错误:JavaScript 内置字符串截断方法为
substring(首字母小写),原有代码写为subString会触发语法报错 - 缺少截断标识:标题截断后没有补充省略号,用户无法感知标题被折叠,体验较差
修正后完整脚本
let postCount = 5; function funcrct(JSON) { const POSTS = JSON.feed.entry; let postTitle, postUrl = ""; let rpc = document.querySelector(".postList"); for (let i = 0; i < postCount; i++) { POSTS[i].link.forEach((el, i) => { if (el.rel === "alternate") { postTitle = el.title; // 修正截断逻辑:赋值+补充省略标识 if (postTitle.length >= 70) { postTitle = postTitle.substring(0, 69) + '...'; } postUrl = el.href; } }) let thumbnail = POSTS[i].content.$t.match(/(http)?s?:?(\/\/[^"']*\.(?:webp))/)[0]; rpc.innerHTML += `<li> <a href="${postUrl}"><figure> <img src="${thumbnail}" alt="${postTitle}"/> <figcaption> ${postTitle}</figcaption></figure></a> </li>`; } } var url = document.location.origin; var fsrc = document.createElement("script"); fsrc.src = `${url}/feeds/posts/default?alt=json-in-script&start-index=1&max-results=${postCount}&callback=funcrct`; document.body.appendChild(fsrc);
可选样式兜底方案
为了避免特殊场景下JS截断失效导致布局错乱,可以新增CSS规则做双重保险,强制标题溢出隐藏:
.postList figcaption { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 100%; }
内容的提问来源于stack exchange,提问作者awakening
相关产品推荐
相关产品推荐

