js实现title
实现动态修改页面标题
使用JavaScript修改页面标题可以通过直接操作document.title属性完成。以下是一个基础示例:
document.title = "新的页面标题";
监听标题变化
如果需要监听标题变化并执行操作,可以结合MutationObserver实现:

const observer = new MutationObserver(function(mutations) {
console.log("标题已更改为:", document.title);
});
observer.observe(document.querySelector('title'), {
childList: true
});
根据路由动态设置标题
在单页应用(SPA)中,通常需要根据路由变化更新标题:
// 假设使用History API
window.addEventListener('popstate', function() {
const routeTitles = {
'/home': '首页',
'/about': '关于我们'
};
document.title = routeTitles[window.location.pathname] || '默认标题';
});
实现标题闪烁效果
通过定时器可以实现标题闪烁的提醒效果:

let originalTitle = document.title;
let isBlinking = false;
function blinkTitle(newText, interval = 1000) {
if(isBlinking) return;
isBlinking = true;
let visible = true;
const blinkInterval = setInterval(() => {
document.title = visible ? newText : originalTitle;
visible = !visible;
}, interval);
// 停止闪烁的函数
return function stopBlinking() {
clearInterval(blinkInterval);
document.title = originalTitle;
isBlinking = false;
};
}
// 使用示例
const stopBlink = blinkTitle("新消息提醒!");
// 调用stopBlink()停止闪烁
支持多语言标题
对于多语言网站,可以根据用户语言偏好设置标题:
const i18nTitles = {
en: {
home: "Home Page",
about: "About Us"
},
zh: {
home: "首页",
about: "关于我们"
}
};
function setLocalizedTitle(pageKey, lang = 'en') {
document.title = i18nTitles[lang][pageKey] || pageKey;
}
兼容SEO的最佳实践
修改标题时需考虑SEO影响,建议:
- 确保标题与页面内容相关
- 避免频繁修改标题
- 标题长度控制在60个字符以内
- 包含主要关键词但不要堆砌
// 示例:SEO友好的标题设置
function setSEOTitle(mainKeyword, description) {
document.title = `${mainKeyword} | ${description}`.substring(0, 60);
}






