倒计时的格式是:离2015年还有 xx年 xx月 xx天 xx小时 xx分钟 xx秒。我想问的是,这个 xx天怎么实现,因为别的 xx年 xx月 xx小时 xx分钟 xx秒,它们都有一个固定的周期。但是不同的月份有不同的天数,所以这个天数怎么得出,难道写个switch语句一点点判断。求大侠指教。有源码更好。javascriptfunction

解决方案 »

  1.   

    怎么不对!
    <html>
    <head>
    <script type="text/javascript">
    function setTime()
    {
        var d = document.getElementById('time');
        if (d){
            var now = new Date();
            var seconds = targetTime.getSeconds() - now.getSeconds();
            var minutes = targetTime.getMinutes() - now.getMinutes();
            if (seconds < 0){
                minutes--;
                seconds += 60;
            }
            var hours = targetTime.getHours() - now.getHours();
            if (minutes < 0){
                hours--;
                minutes += 60;
            }
            var date = targetTime.getDate() - now.getDate();
            if (hours < 0){
                date--;
                hours += 24;
            }
            var month = targetTime.getMonth() - now.getMonth();
            if (date < 0){
                month--;
                var nextDate = new Date();
                nextDate.setMonth(nextDate.getMonth() + 1);
                nextDate.setDate(0);
                date += nextDate.getDate();
            }
            var year = targetTime.getYear() - now.getYear();
            if (month < 0){
                year--;
                month += 12;
            }
            if (year < 0){
                d.innerText = '超啦!';
                return;
            }
            d.innerText = '离' + targetTime.toLocaleString() + '还有'+ year + '年' +
                month + '个月' +
                date + '天' +
                hours + '小时' +
                minutes + '分钟' +
                seconds + '秒';
        }
    }
    var targetTime = new Date('2015/1/1');
    setInterval(setTime, 1000);
    </script>
    </head><body>
    <form>
    <span id='time'></span> 
    </form>
    </body></html>闰年管它干吗,本来就是一年多少天不管了。