我正在尝试制作一个只有数字并每天更新(减去 1 )的 Chrome 扩展
我已经让它打印出数字作为 chrome 扩展背景,但现在我正在尝试每天更改数字。 我有 4 个文件:
background.js
icon_19.png
jquery.js
list .json
icon_19.png 是必需的,因为为了使用 Canvas 设置扩展程序的背景,您必须首先拥有一个图像。
jquery.js 只是 javascript 库。我把它包括在内。
manifest.json:
{
"manifest_version": 2,
"name": "Countdown",
"description": "This extension countdowns to my death.",
"version": "1.0",
"background": {
"scripts":["background.js"]
},
"browser_action": {
"default_title": "Countdown",
"default_popup": "countdown.html"
}
}
背景.js:
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var myDeath = new Date();
myDeath.setMonth(7);
myDeath.setDate(16);
var canvas = document.createElement('canvas');
canvas.width = 19;
canvas.height = 19;
var ctx = canvas.getContext('2d');
var start = 18;
ctx.font='20px Arial';
setInterval(function() {
ctx.clearRect(0,0,19,19);
ctx.fillText(start, 0, 19, 19);
start--;
chrome.browserAction.setIcon({
imageData: ctx.getImageData(0, 0, 19, 19)
})
}, 1000);
它的作用是打印数字(开始)作为 chrome 扩展背景。然后开始每1秒倒计时。它也有效。我只需要知道如何做到这一点,以便它只在接下来的每一天减去 -1,直到我点击 myDeath。有谁知道如何每天将数字更改1吗?我希望当我打开 chrome 时,数字每天都会下降一次。提前致谢!! :)
最佳答案
一些注意事项:
- 您需要增加刷新间隔。每秒刷新一天毫无意义。我已将其设置为每 12 小时一次,但您可以将其更改为您想要的次数。
- 计算日期差应该是它自己的函数,以便您可以重复调用它。这使得代码更容易维护,因为死亡日期数据与使用它的代码是分开的。
- 为了便于维护,我已将死亡日期配置分离到其自己的对象中。
death.month
包含 1 到 12 之间的值。请参阅第一个代码注释。death.year
是可选的,该参数在函数中不是必需的。background.js
之外的任何内容都不需要更改。
背景.js
var death = {
day: 16,
month: 8
}
var intervalHours = 12;
function getRemainingDays(d, m, y){
var today = new Date();
var myDeath = new Date();
myDeath.setMonth(m-1); // Month is a range from 0-11; this lets you configure using a range from 1-12
myDeath.setDate(d);
if(typeof y !== "undefined"){ // if death.year is not provided, just use the current year
myDeath.setYear(y);
}
return (myDeath-today)/86400000; // (myDeath-today) produces a result in milliseconds, this turns that into days
}
var canvas = document.createElement('canvas');
canvas.width = 19;
canvas.height = 19;
var ctx = canvas.getContext('2d');
ctx.font='20px Arial';
setInterval(function() {
ctx.clearRect(0,0,19,19);
ctx.fillText(getRemainingDays(death.day, death.month), 0, 19, 19);
chrome.browserAction.setIcon({
imageData: ctx.getImageData(0, 0, 19, 19)
})
}, (intervalHours*3600000)); // converts hours to milliseconds
关于javascript - 倒计时一天,每天更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17959765/