这是我的HTML和脚本:
<div class="gk-cols" data-cols="3">
<div class="myclass">
<a href="#" class="otherclass"><img alt="myalt" src="myimage.png"> <strong><span data-sr="enter bottom" data-count=""><div id="counter_1"></div></span><span>units <strong><span class="anotherclass">Name</span></strong> used</span></strong></a>
</div>
<div class="myclass">
<a href="#" class="otherclass"><img alt="myalt" src="myimage.png"> <strong><span data-sr="enter bottom" data-count=""><div id="counter_2"></div></span><span>units <strong><span class="anotherclass">Name</span></strong> used</span></strong></a>
</div>
<div class="myclass">
<img alt="myalt" src="myimage.png"> <strong><span data-sr="enter bottom" data-count=""><div id="counter_3">
mytext
<div class="otherclass">
<span class="anotherclass" style="display: inline-block; visibility: visible; position: relative;">
<span class="classissima"></span>
<span class="classagain">
other text
</span>
<svg version="1.1" viewBox="0 0 92 92" class="loader">
<circle class="bar" cx="46" cy="46" r="43"/>
<circle class="path" cx="46" cy="46" r="43"/>
</svg>
</span>
</div>
</div></span><span> text<strong><psna class="classagain">Name</psna></strong> used</span></strong>
</div>
</div>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
var START_DATE_1 = new Date('July 18, 2016 10:30:00').getTime(); // put in the starting date here
var INTERVAL_1 = 4; // in seconds
var INCREMENT_1 = 1; // increase per tick
var START_VALUE_1 = 0; // initial value when it's the start date
var msInterval_1 = INTERVAL_1 * 1200;
var now_1 = Date.now();
var count_1 = Math.trunc((now_1 - START_DATE_1) / msInterval_1) * INCREMENT_1 + START_VALUE_1;
function formatNumber(number) {
return new Intl.NumberFormat('it').format(number);
}
document.getElementById('counter_1').textContent = formatNumber(count_1);
setInterval(function() {
count_1 += INCREMENT_1;
document.getElementById('counter_1').textContent = formatNumber(count_1);
}, msInterval_1);
var START_DATE_2 = new Date('July 18, 2016 10:30:00').getTime(); // put in the starting date here
var INTERVAL_2 = 7; // in seconds
var INCREMENT_2 = 1; // increase per tick
var START_VALUE_2 = 0; // initial value when it's the start date
var msInterval_2 = INTERVAL_2 * 2500;
var now_2 = Date.now();
var count_2 = Math.trunc((now_2 - START_DATE_2) / msInterval_2) * INCREMENT_2 + START_VALUE_2;
function formatNumber(number) {
return new Intl.NumberFormat('it').format(number);
}
document.getElementById('counter_2').textContent = formatNumber(count_2);
setInterval(function() {
count_2 += INCREMENT_2;
document.getElementById('counter_2').textContent = formatNumber(count_2);
}, msInterval_2);
});
</script>
现在,脚本在桌面视图中工作正常,但是只要我减小窗口大小(移动大小)并重新加载,或者只是用智能手机检查我的页面,我就会收到错误:“JavaScript:TypeError:document.getElementById (...)为空“并且计数器也是空的。
为什么?