javascript倒计时器与设定时间

时间:2018-02-14 12:59:51

标签: javascript

我正在尝试为网站创建24小时的促销时间。 我已经想出如何通过当前时间开始午夜开始的日常计时器,但我需要更加灵活,并能够在一天的随机时间启动它。 我目前得到的代码:

  <div id="countdown_hours"></div>
  <script>
  setInterval(function time(){
  var d = new Date();
  var hours = 24 - d.getHours();
  var minutes = 60 - d.getMinutes();
  if((minutes + '').length == 1){
    minutes = '0' + minutes;
  }
  var seconds = 60 - d.getSeconds();
  if((seconds + '').length == 1){
        seconds = '0' + seconds;
  }
  document.getElementById("countdown_hours").innerHTML =
             '<div class="clockcontainer">'
              + '<p>Promo</p>'
              + '<div class="clock">'
              + '<div class="count"><span>'
              + hours
              + '</span> <label> Hours</label> </div>'
              + '<div class="count"><span>'
              + minutes
              + '</span> <label> Minutes</label> </div>'
              + '<div class="count"><span>'
              + seconds
              +'</span> <label> Seconds</label> </div>'
              + '</div>'
              + '</div>';
}, 1000);
  </script>

所以我想我需要将一个变量设置为我的倒计时时间,例如var time = 24,然后从小时,分钟和秒的变化时间开始倒计时。任何人都能指出我如何实现这个目标的正确方向吗?

3 个答案:

答案 0 :(得分:0)

您可以使用jQuery Countdown

 var newYear = new Date(); 
newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1); 
$('#defaultCountdown').countdown({until: newYear}); 

答案 1 :(得分:0)

你可以这样做:

// A countdown object
const CountDown = function (target) {
    const endTime = new Date(target);

    // Return a date object with the time left
    this.getTime = () => new Date(endTime - Date.now());
}

// This simply a method of setting the date to 24 hours
// See https://stackoverflow.com/a/3674550/3533202
const tomorrow = new Date();
tomorrow.setDate(
    new Date().getDate() + 1
);

// Initialise the countdown object
const countdown = new CountDown(tomorrow);

// Get the element you want to change
const elem = document.getElementById("countdown_hours");

setInterval(function (elem) {
    const timeLeft = countdown.getTime();

    // Get the time left in numerical format
    const hours = timeLeft.getHours();
    const minutes = timeLeft.getMinutes();
    const seconds = timeLeft.getSeconds();

    // Now populate your element
    // This is a template literal, see:
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
    console.log(`
    <div class="clockcontainer">
        <p>Promo</p>
        <div class="clock">
            <div class="count">
                <span>${hours}</span>
                <label> Hours</label>
            </div>
            <div class="count">
                <span>${minutes}</span>
                <label> Minutes</label>
            </div>
            <div class="count">
                <span>${seconds}</span>
                <label> Seconds</label>
            </div>
        </div>
    </div>`)
}, 1000, elem)

答案 2 :(得分:0)

您可以按特定类标记所有倒计时,并将数据属性中的倒计时时间戳传递给unix时间戳。

我强烈建议在javascript中使用moment.js库进行时间操作(它具有丰富的API,它构建在默认的Date类之上以实现兼容性,几乎可以在任何地方运行并支持文本本地化)。

简单示例:

&#13;
&#13;
function countdown(el, interval) {
  const end = moment.unix(el.dataset.end);
  const dur = moment.duration(end.diff(moment()));
  let html = ''
  if(dur.hours() > 0) {
  	const hours = Math.floor(dur.asHours(true));
  	html += hours + ' ' + plural(hours, 'hour') + ', ';
  }
  if(dur.minutes() > 0) {
  	html += dur.minutes() + ' ' + plural(dur.minutes(), 'minute') + ', ';
  }
  if(dur.seconds() > 0) {
  	html += dur.seconds() + ' ' + plural(dur.seconds(), 'second') + ', ';
  }
  html = html.slice(0, -2);
  
  if(dur <= 0) {
  	clearInterval(interval);
  	html = 'Now';
  }
  el.innerHTML = html;
}

function plural(n, word) {
	return word + ((n === 1) ? '' : 's');
}

const elements = document.getElementsByClassName('countdown');
Array.prototype.forEach.call(elements, function (el) {
	const interval = setInterval(function() {
    countdown(el, interval);
  }, 1000);
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<div class="countdown" data-end="1519302600"></div>
<div class="countdown" data-end="1519776030"></div>
&#13;
&#13;
&#13;

jsFiddle链接