我试图在扩展程序的下拉列表中显示倒计时,但有两个问题:
A) 我的脚本返回错误,因为它无法通过 id 从下拉列表的内容中获取元素
B) 即使关闭下拉列表并重新打开它,如何保持倒计时运行?
这是我的 JS:
// variables for time units
var days, hours, minutes, seconds;
// get tag element
var countdown = document.getElementById("countdown");
// update the tag with id "countdown" every 1 second
setInterval(function () {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
countdown.innerHTML = days + "d, " + hours + "h, "
+ minutes + "m, " + seconds + "s";
}, 1000);
在 HTML 中我有:
<span id="countdown"></div>
我得到的错误是: 未捕获类型错误:无法将属性“innerHTML”设置为 null
非常感谢任何帮助!谢谢 !!
最佳答案
A)我怀疑您的代码被放置(在放置的脚本内)“head”部分内的某个位置。在这种情况下,您所要做的就是将所有代码放入 window.onload = function () { ... }
或 DOMContentLoaded
监听器
B) 这更复杂。我认为最好的解决方案是在后台页面创建计数器并每秒将消息从它发送到弹出页面。
关于javascript - 在 Chrome 扩展程序下拉列表中显示倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21973320/