[英]How to animate position of browser tab's title on tab change
I'm trying to animate the browser tab's title when that tab has been inactive for more than 1 second.当该选项卡处于非活动状态超过 1 秒时,我正在尝试为该选项卡的标题设置动画。 When I add the following snippet to the console, it works perfectly fine.
当我将以下代码段添加到控制台时,它工作得很好。 However, when I try to call this inside an eventlistener for "visibilitychange", it does change the title however it fails to animate.
但是,当我尝试在“visibilitychange”的事件侦听器中调用它时,它确实更改了标题,但无法设置动画。
msg = "Don't forget us" + msg;
position = 0;
function scrolltitle() {
document.title = msg.substring(position, msg.length) + msg.substring(0, position); position++;
if (position > msg.length);
position = 0
window.setTimeout("scrolltitle()",170);
}
scrolltitle();
Here is the full code I'm trying to run but failing to do so with the desired behaviour of animation:这是我尝试运行的完整代码,但未能实现所需的动画行为:
const animate = () => {
msg = ' ';
msg = "Don't forget us" + msg;
position = 0;
function scrolltitle() {
document.title = msg.substring(position, msg.length) + msg.substring(0, position); position++;
if (position > msg.length);
position = 0
window.setTimeout("scrolltitle()",170);
}
scrolltitle();
};
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
setTimeout(() => {
animate();
}, 1000);
}
});```
initialize your variable with let
, your code doesn't work because position
variable is not being updated用
let
初始化你的变量,你的代码不起作用,因为position
变量没有被更新
const animate = () => {
let msg = " ";
msg = "Don't forget us" + msg;
let position = 0;
function scrolltitle() {
console.log(position, msg.length);
document.title =
msg.substring(position, msg.length) + msg.substring(0, position);
position++;
if (position > msg.length) position = 0;
setTimeout(() => {
scrolltitle();
}, 170);
}
scrolltitle();
};
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
setTimeout(() => {
animate();
}, 1000);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.