网页动机如何运作?

时间:2015-09-12 04:51:39

标签: javascript html css

我的朋友约书亚把这个网页称为动机。链接是:http://joshuaraichur.com/motivation/

任何人都可以向我解释他是如何告诉你离开小数点后第5位的天数吗?

代码在github上:https://github.com/raichur/motivation

编辑:

有谁能告诉我caluclate预期寿命函数是如何工作的?

1 个答案:

答案 0 :(得分:1)

首先,他定义了一些变量来传递JS计算:

// YOU NEED TO CHANGE THESE VARIABLES //
var sleepingTimeHours = 12, // The hour you sleep. In my case I sleep at 12:00pm
sleepingTimeMinutes = 00, // The minutes remaining for the time you sleep.
yearOfBirth = 1997, // Year of birth
monthOfBirth = 8, // Month of birth
dayOfBirth = 31; // Day of birth

以毫秒为单位保存时间的变量,以及到达DOM树中元素的快捷方式:

`

var year = 31558464000, // Milliseconds in a year
    day = 86400000, // Milliseconds in a day
    hour = 3600000, // Milliseconds in an hour
    ageElement = document.getElementById("age"),
    hoursLeftTodayElement = document.getElementById("hoursLeftToday"),
    quoteText = document.getElementById("quoteText"),
    quoteAuthor = document.getElementById("quoteAuthor"),
    currentDateElement = document.getElementById("currentDate"),
    currentTimeElement = document.getElementById("currentTime"),
    yearsToLive = document.getElementById("yearsToLive"),
    daysToLive = document.getElementById("daysToLive"),
    sleepingTimeHourVal = document.getElementById("sleepingTimeHour"),
    sleepingTimeMinutesVal = document.getElementById("sleepingTimeMinutes"),
    yearOfBirthVal = document.getElementById("yearOfBirth"),
    monthOfBirthVal = document.getElementById("monthOfBirth"),
    dayOfBirthVal = document.getElementById("dayOfBirth");`

根据第一个代码块中定义的变量计算年龄:

// Calculate age
function calculateAge(yearOfBirth, monthOfBirth, dayOfBirth, now) {
var myAge = now - (new Date(yearOfBirth, monthOfBirth, dayOfBirth));
var ageString = (myAge / year).toString().substring(0, 11);
ageString = ageString < 0 ? 0 : ageString;
return ageString;
}

然后,基于平均82岁生命的预期寿命:

// Calculate life expectancy based on average
function calculateLifeExpectancy(age) {
var expectancy = (82 - age).toString().substring(0, 11); // Average of 30k days (82 years)
expectancy = expectancy < 0 ? 0 : expectancy;
return expectancy;
}

最后,小数的魔力和打印结果在这里完成!

´setInterval(function getStuff(){
   var now = Date.now(),
   nowNew = new Date();
   var age = calculateAge(yearOfBirth, monthOfBirth, dayOfBirth, now);
   ageElement.innerHTML = age;
   hoursLeftTodayElement.innerHTML = hoursLeftToday(sleepingTimeHours, sleepingTimeMinutes, nowNew);
   currentDateElement.innerHTML = currentDay(nowNew);
   currentTimeElement.innerHTML = currentDate(nowNew);
   //THE YEARS TO LIVE CALCULATION IS DONE HERE
   yearsToLive.innerHTML = calculateLifeExpectancy(age);
   daysToLive.innerHTML = addComma(calculateLifeExpectancy(age)*365.25).toString().substring(0, 12);
   }, 100);´