Как добавить счетчик к значениям - PullRequest
1 голос
/ 06 апреля 2020

Как указано в заголовке, как добавить анимацию отсчета к следующим элементам: Проверенное положительное число смертей среди населения Процент смертей положительно протестированных людей Последнее обновление данных

Числа являются динамическими c, а не stati c, вот где я заблудился.

Спасибо за вашу помощь. Извините, но я новичок в кодировании с Javascript, Json и использовании API.

window.addEventListener("load", function() {
  document.getElementById("countrySel").addEventListener("change", getCovidStats);
  document.getElementById("countrySel").value = "169";
  getCovidStats()
})

function getCovidStats() {
  const cc = document.getElementById("countrySel").value;
  if (cc === "") return;

  fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations/' + cc)
    .then(function(resp) {
      return resp.json()
    })
    .then(function(data) {
      let population = data.location.country_population;
      let update = data.location.last_updated;
      let confirmedCases = data.location.latest.confirmed;
      let deaths = data.location.latest.deaths;

      document.getElementById('inwoners').innerHTML = population.toLocaleString('en');
      document.getElementById('update').innerHTML = update.substr(0, 10);
      document.getElementById('patienten').innerHTML = confirmedCases.toLocaleString('en');
      document.getElementById('doden').innerHTML = deaths.toLocaleString('en');
      document.getElementById('procent').innerHTML = ((Number(deaths) / Number(confirmedCases)) * 100).toLocaleString("en", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }) + "%";
    })
    .catch(function() {
      console.log("error");
    })
  setInterval(getCovidStats, 43200000) // update every 12 hours
}
* {
  margin: 0;
  padding: 0;
}

html {
  height: 100%;
  width: 100%;
}

h1,
h2 {
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
  text-align: center;
  padding-bottom: 20px;
  font-size: 250%;
}

.subtitle,
.over {
  padding: 20px;
  font-size: 150%;
}

body {
  background-color: #FFDC56;
}

div {
  padding: 20px;
}


/* Add a black background color to the top navigation */

.topnav {
  background-color: #005A9C;
  overflow: hidden;
  font-family: 'Roboto', sans-serif;
  font-size: 75%;
}

.logo {
  float: left;
}


/* Style the links inside the navigation bar */

.topnav a {
  float: right;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}


/* Change the color of links on hover */

.topnav a:hover {
  background-color: #FFDC56;
  color: black;
}


/* Add a color to the active/current link */

.topnav a.active {
  background-color: #4CAF50;
  color: white;
}

.stats-container {
  text-align: center;
  float: right;
  display: inline-block;
}

.location-container {
  display: inline-block;
}

.data-container {
  border: 2px solid #005A9C;
  margin-right: 30%;
  margin-left: 30%;
}

h4,
{
  font-size: 85%;
  color: gray;
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
  text-align: center;
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 5px;
}

.over {
  font-family: 'Roboto', sans-serif;
  font-size: 100%;
  text-align: center;
}

.footer {
  font-family: 'Roboto', sans-serif;
  bottom: 0;
  font-size: 75%;
  padding: 5px;
}

.maatregelen {
  width: 35%;
  display: block;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

.maatregelen-caption {
  text-align: center;
  font-family: 'Roboto', sans-serif;
  font-size: 80%;
}
<!DOCTYPE html>
<html>

<head>
  <title>Coronavirus Statistieken</title>
  <meta charset="UTF-8">
  <link rel="shortcut icon" href="masker-emoji.png">
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400&display=swap" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="styles.css">
  <script type="text/javascript" src="app.js"></script>
  <script type="text/javascript" src="loader.js"></script>

</head>

<body>
  <div class="topnav">
    <h1 class="logo">Coronavirus</h1>
    <a href="over.html">about</a>
    <a class="active" href="index.html">stats</a>
  </div>

  <h2 class="subtitle">Title</h2>
  <div class="data-container">
    <div class="stats-container">
      <h4>Tested positive</h4>
      <h1 id="patienten"></h1>
      <h4>Deaths</h4>
      <h1 id="doden"></h1>
      <h4>Percentage of deaths of positive tested people</h4>
      <h1 id="procent"></h1>
    </div>
    <div class="location-container">
      <h4>country</h4>
      <h1 id="country"><label for="countrySel">Country:</label>
        <select id="countrySel">
          <option value="169">?? </option>
          <option value="120">?? </option>
          <option value="116">?? </option>
          <option value="201">?? </option>
          <option value="137">?? </option>
          <option value="187">?? </option>
          <option value="143">?? </option>
          <option value="225">?? </option>
        </select>
      </h1>
      <h4>population</h4>
      <h1 id="inwoners"></h1>
      <h4>updated on</h4>
      <h1 id="update"></h1>
    </div>
  </div>
  <h1 class="footer">Footer</h1>
</body>

</html>

Ответы [ 2 ]

0 голосов
/ 06 апреля 2020

Это можно сделать разными способами.

  1. Звоните каждые n секунд, чтобы получить последние данные на основе выбранной страны и обновить счетчик.
  2. Создайте шаблон для подписки sh. Более подробная информация здесь: https://www.enterpriseintegrationpatterns.com/patterns/messaging/PublishSubscribeChannel.html

Я бы выбрал вариант 2 выше, потому что он имеет много преимуществ, так как все браузеры, подключенные к этой конечной точке, будут обновлены, данные консистенция, чтобы назвать несколько. Но мы должны подумать и о том, чтобы поставить туда надежного абонента. Ссылка охватывает много хороших вещей.

Любой другой способ, пожалуйста, поделитесь здесь!

0 голосов
/ 06 апреля 2020

Я сделал это для вас

трудно увидеть в выводе фрагмента - go во весь экран и перейти в другую страну

let tId;
window.addEventListener("load", function() {
  document.getElementById("countrySel").addEventListener("change", getCovidStats);
  document.getElementById("countrySel").value = "169";
  getCovidStats()
})

function countUp() {
  cnt += 300;
  let done = 0;
  let iMax = +document.getElementById('inwoners').getAttribute("max");
  if (cnt < iMax) document.getElementById('inwoners').innerText = cnt.toLocaleString('en');
  else done++
    let pMax = +document.getElementById('patienten').getAttribute("max");
  if (cnt < pMax) document.getElementById('patienten').innerText = cnt.toLocaleString('en');
  else done++
    let dMax = +document.getElementById('doden').getAttribute("max");
  if (cnt < dMax) document.getElementById('doden').innerText = cnt.toLocaleString('en');
  else done++



    document.getElementById('procent').innerHTML = ((Number(document.getElementById('doden').innerText.replace(/\D/g, "")) / Number(document.getElementById('patienten').innerText.replace(/\D/g, ""))) * 100).toLocaleString("en", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }) + "%";
  if (done === 3) clearInterval(tId);
}


function getCovidStats() {
  const cc = document.getElementById("countrySel").value;
  if (cc === "") return;

  fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations/' + cc)
    .then(function(resp) {
      return resp.json()
    })
    .then(function(data) {
      let population = data.location.country_population;
      let update = data.location.last_updated;
      let confirmedCases = data.location.latest.confirmed;
      let deaths = data.location.latest.deaths;

      document.getElementById('inwoners').innerText = population.toLocaleString('en');
      document.getElementById('update').innerText = update.substr(0, 10);
      document.getElementById('patienten').innerText =
        document.getElementById('patienten').setAttribute("max", confirmedCases)
      document.getElementById('doden').innerText = 0;
      document.getElementById('doden').setAttribute("max", deaths)
      document.getElementById('procent').innerText = 0 + "%"
      cnt = 0;
      tId = setInterval(countUp, 10);
    })
    .catch(function() {
      console.log("error");
    })
  setInterval(getCovidStats, 43200000) // update every 12 hours
}
* {
  margin: 0;
  padding: 0;
}

html {
  height: 100%;
  width: 100%;
}

h1,
h2 {
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
  text-align: center;
  padding-bottom: 20px;
  font-size: 250%;
}

.subtitle,
.over {
  padding: 20px;
  font-size: 150%;
}

body {
  background-color: #FFDC56;
}

div {
  padding: 20px;
}


/* Add a black background color to the top navigation */

.topnav {
  background-color: #005A9C;
  overflow: hidden;
  font-family: 'Roboto', sans-serif;
  font-size: 75%;
}

.logo {
  float: left;
}


/* Style the links inside the navigation bar */

.topnav a {
  float: right;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}


/* Change the color of links on hover */

.topnav a:hover {
  background-color: #FFDC56;
  color: black;
}


/* Add a color to the active/current link */

.topnav a.active {
  background-color: #4CAF50;
  color: white;
}

.stats-container {
  text-align: center;
  float: right;
  display: inline-block;
}

.location-container {
  display: inline-block;
}

.data-container {
  border: 2px solid #005A9C;
  margin-right: 30%;
  margin-left: 30%;
}

h4,
{
  font-size: 85%;
  color: gray;
  font-family: 'Roboto', sans-serif;
  font-weight: 300;
  text-align: center;
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 5px;
}

.over {
  font-family: 'Roboto', sans-serif;
  font-size: 100%;
  text-align: center;
}

.footer {
  font-family: 'Roboto', sans-serif;
  bottom: 0;
  font-size: 75%;
  padding: 5px;
}

.maatregelen {
  width: 35%;
  display: block;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

.maatregelen-caption {
  text-align: center;
  font-family: 'Roboto', sans-serif;
  font-size: 80%;
}
<!DOCTYPE html>
<html>

<head>
  <title>Coronavirus Statistieken</title>
  <meta charset="UTF-8">
  <link rel="shortcut icon" href="masker-emoji.png">
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400&display=swap" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="styles.css">
  <script type="text/javascript" src="app.js"></script>
  <script type="text/javascript" src="loader.js"></script>

</head>

<body>
  <div class="topnav">
    <h1 class="logo">Coronavirus</h1>
    <a href="over.html">about</a>
    <a class="active" href="index.html">stats</a>
  </div>

  <h2 class="subtitle">Title</h2>
  <div class="data-container">
    <div class="stats-container">
      <h4>Tested positive</h4>
      <h1 id="patienten"></h1>
      <h4>Deaths</h4>
      <h1 id="doden"></h1>
      <h4>Percentage of deaths of positive tested people</h4>
      <h1 id="procent"></h1>
    </div>
    <div class="location-container">
      <h4>country</h4>
      <h1 id="country"><label for="countrySel">Country:</label>
        <select id="countrySel">
          <option value="169">?? </option>
          <option value="120">?? </option>
          <option value="116">?? </option>
          <option value="201">?? </option>
          <option value="137">?? </option>
          <option value="187">?? </option>
          <option value="143">?? </option>
          <option value="225">?? </option>
        </select>
      </h1>
      <h4>population</h4>
      <h1 id="inwoners"></h1>
      <h4>updated on</h4>
      <h1 id="update"></h1>
    </div>
  </div>
  <h1 class="footer">Footer</h1>
</body>

</html>
...