实现标题Title的闪烁
🔺在两个标题之间来回切换(甚至多个)
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>♥做自己的宇宙♥</title>
<!-- 标题效果 -->
<script>
//定义一个值接收定时器的返回值,默认不赋值给他,所以为NULL
var intervalTitle;
//一标题
const title1 = document.title;
//二标题
const title2 = "♥成为自己想成为的人♥";
//”闪烁“函数 此函数用于标题切换
function ChangeTitle() {
if (document.title === title1) {
document.title = title2;
} else if (document.title === title2) {
document.title = title1;
}
}
//“开始闪烁”函数 此函数用于标题开始切换
const StartChange = function () {
//此时intervalTitle为NULL,进入if
if (!intervalTitle) {
console.log('开始');
//定时器开启闪烁和闪烁延迟时间
intervalTitle = setInterval(ChangeTitle, 1500);
}
}
//开始闪烁
StartChange();
</script>
</head>
实现离开此页面标题更改
//离开页面会出现的标题
document.addEventListener('visibilitychange', function () {
if (document.visibilityState == 'hidden') {
normal_title = document.title;//document.title用于获取当前标题
document.title = 'QvQ这就要走了吗?';
} else {
document.title = normal_title;
}
});
将两者融合
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>♥做自己的宇宙♥</title>
<!-- 标题效果 -->
<script>
var intervalTitle;
//一号标题
const title1 = document.title;
//二号标题
const title2 = "♥成为自己想成为的人♥";
//开始闪烁函数
//离开页面会出现的标题
document.addEventListener('visibilitychange', function () {
if (document.visibilityState == 'hidden') {
normal_title = document.title;
document.title = 'QvQ这就要走了吗?';
//离开页面,清空计数器
clearInterval(intervalTitle);
intervalTitle = null;
} else {
document.title = normal_title;
//回到页面开始闪烁
StartChange();
}
});
//闪烁函数
function ChangeTitle() {
if (document.title === title1) {
document.title = title2;
} else if (document.title === title2) {
document.title = title1;
}
}
const StartChange = function () {
if (!intervalTitle) {
console.log('开始');
intervalTitle = setInterval(ChangeTitle, 1500);
}
}
//开始闪烁
StartChange();
</script>
</head>