HTML / Javascript обратный индикатор с датой обратного отсчета - PullRequest
0 голосов
/ 09 октября 2018

Я не могу найти что-то, что создает индикатор выполнения, пока он приближается к дате обратного отсчета.

Я нашел два отдельных примера, которые можно объединить, но я не знаю, как:
Обратный отсчет - https://www.jqueryscript.net/time-clock/Minimal-jQuery-Any-Date-Countdown-Timer-Plugin-countdown.html (1-й пример, ПРОСТОЙ ОБРАЗ ТЕКСТА)
Индикатор выполнения - https://jsfiddle.net/zessx/4PKEB/1/:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {    
function progress(timeleft, timetotal, $element) {
	var progressBarWidth = (timeleft / timetotal) * $element.width();
    $element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear').html(timeleft + " seconds to go");
    if(timeleft > 0) {
        setTimeout(function() {
            progress(timeleft - 1, timetotal, $element);
        }, 1000);
    }
};
progress(20, 20, $('#progressBar'));
});
</script>

<style>
#progressBar {
    width: 90%;
    margin: 10px auto;
    height: 22px;
    background-color: #0A5F44;
}

#progressBar div {
    height: 100%;
    text-align: right;
    padding: 0;
    line-height: 22px; /* same as #progressBar height if we want text middle aligned */
    width: 0;
    background-color: #CBEA00;
    box-sizing: border-box;
}
</style>

<div id="progressBar">
    <div></div>
</div>

ВОПРОС ОБНОВЛЕНИЯ
Позвольте мне объяснить немного больше, что мне нужно.
Мне нужно объединить код из обеих ссылок и получитьчто-то вроде этого:
enter image description here
Итак, наконец, мне нужно иметь текст обратного отсчета (обведено синим цветом), чтобы на самом деле соответствовать уменьшающемуся цвету (обведенному красным) вИндикатор выполнения.
В нескольких словах мне нужен индикатор выполнения с текстом в нем, считая дни, часы, минуты, секунды до определенной даты, а не в течение определенного периода времени.

Весь мой html:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Countdown Plugin Examples</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.jqueryscript.net/demo/Minimal-jQuery-Any-Date-Countdown-Timer-Plugin-countdown/dest/jquery.countdown.js"></script>

<script type="text/javascript">
$(function() {
    var endDate = "December 31, 2088 23:59:59";

    $('.countdown.simple').countdown({ date: endDate });

    // End time for diff purposes
    var endTimeDiff = new Date().getTime() + 15000;
    // This is server's time
    var timeThere = new Date();
    // This is client's time (delayed)
    var timeHere = new Date(timeThere.getTime() - 5434);
    // Get the difference between client time and server time
    var diff_ms = timeHere.getTime() - timeThere.getTime();
    // Get the rounded difference in seconds
    var diff_s = diff_ms / 1000 | 0;
});

$(document).ready(function() {
    function progress(timeleft, timetotal, $element) {
        //var progressBarWidth = timeleft * $element.width() / timetotal;
        var progressBarWidth = (timeleft / timetotal) * $element.width();
        $element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear');
        if(timeleft > 0) {
            setTimeout(function() {
                progress(timeleft - 1, timetotal, $element);
            }, 1000);
        }
    };
    progress(20, 20, $('#progressBar'));
});
</script>

<style>
body {
    font: 13px/1.4 'Helvetica Neue', 'Helvetica','Arial', sans-serif;
    color: #333;
}
.container {
    width: 520px;
    margin: auto;
}
h1 {
    border-bottom: 1px solid #d9d9d9;
}
h2{
    position: relative;;
    font-size: 16px;
    font-weight: normal;
    text-transform: uppercase;
}
h2:before{
    content: '\2192';
    position: absolute;
    left: -20px;
    font-size: 0.9em;
}
a {
    color: #be2221;
    text-decoration: none;
}

.simple {
    font-size: 20px;
    background: #27ae60;
    padding: 0.5em 0.7em;
    color: #ecf0f1;
    margin-bottom: 50px;
    -webkit-transition: background 0.5s ease-out;
    transition: background 0.5s ease-out;
}
.simple {
    margin-bottom: 50px;
}
.simple div {
    display: inline-block;
    margin-left: 10px;
    font-size: 30px;
    font-weight: 100;
    line-height: 1;
    text-align: right;
}
/* IE7 inline-block hack */
*+html .simple div {
    display: inline;
    zoom: 1;
}
.simple div:first-child {
    margin-left: 0;
}
.simple div span {
    display: block;
    border-top: 1px solid #cecece;
    padding-top: 3px;
    font-size: 12px;
    font-weight: normal;
    text-transform: uppercase;
    text-align: left;
}

#progressBar {
    width: 90%;
    margin: 10px auto;
    height: 22px;
    background-color: #fff;
    border:1px solid #ddd;
}
#progressBar div {
    height: 100%;
    text-align: right;
    line-height: 22px; /* same as #progressBar height if we want text middle aligned */
    width: 0;
    background-color: #CBEA00;
    box-sizing: border-box;
}
</style>
</head>

<body>
<div class="container" style="margin-top:50px;">
    <h2>Simple text countdown</h2>
    <div class="countdown simple" data-date="December 31, 2018 23:59:59"></div>

    <div id="progressBar">
        <div></div>
    </div>
</div>
</body>
</html>

Буду признателен за любую помощь !!

Ответы [ 2 ]

0 голосов
/ 09 октября 2018

Сначала по вашему сценарию

function progress(timeleft, timetotal, $element) {
  var progressBarWidth = (timeleft / timetotal) * $element.width(); //<-- refactor the formula

 // your codes
};

, затем стили:

#progressBar div {
  height: 100%;
  text-align: right;
  padding: 0;    /* remove padding */
  line-height: 22px;
  width: 0;
  background-color: #CBEA00;
  box-sizing: border-box;
}

ОБНОВЛЕНИЕ

$(document).ready(function() {
  function progress(timeleft, timetotal, $element) {
    let progressBarWidth = timeleft / timetotal * $element.width();

    let days = parseInt(timeleft / 86400);
    let hoursLeft = parseInt(timeleft - days * 86400);
    let hours = parseInt(hoursLeft / 3600);
    let minutesLeft = parseInt(hoursLeft - hours * 3600);
    let minutes = parseInt(minutesLeft / 60);
    let seconds = parseInt(timeleft % 60);

    $element
      .find("div")
      .animate(
        { width: progressBarWidth },
        timeleft == timetotal ? 0 : 1000,
        "linear"
      )
      .html(
        `${days} days, ${hours} hours, ${minutes} minutes, ${seconds} seconds`
      );
    if (timeleft > 0)
      setTimeout(() => progress(timeleft - 1, timetotal, $element), 1000);
  }
  progress(60, 60, $("#progressBar"));
});
body {
    font: 13px/1.4 'Helvetica Neue', 'Helvetica','Arial', sans-serif;
    color: #333;
}
.container {
    width: 520px;
    margin: auto;
}
h1 {
    border-bottom: 1px solid #d9d9d9;
}
h2{
    position: relative;;
    font-size: 16px;
    font-weight: normal;
    text-transform: uppercase;
}
h2:before{
    content: '\2192';
    position: absolute;
    left: -20px;
    font-size: 0.9em;
}
a {
    color: #be2221;
    text-decoration: none;
}

.simple {
    font-size: 20px;
    background: #27ae60;
    padding: 0.5em 0.7em;
    color: #ecf0f1;
    margin-bottom: 50px;
    -webkit-transition: background 0.5s ease-out;
    transition: background 0.5s ease-out;
}
.simple {
    margin-bottom: 50px;
}
.simple div {
    display: inline-block;
    margin-left: 10px;
    font-size: 30px;
    font-weight: 100;
    line-height: 1;
    text-align: right;
}
/* IE7 inline-block hack */
*+html .simple div {
    display: inline;
    zoom: 1;
}
.simple div:first-child {
    margin-left: 0;
}
.simple div span {
    display: block;
    border-top: 1px solid #cecece;
    padding-top: 3px;
    font-size: 12px;
    font-weight: normal;
    text-transform: uppercase;
    text-align: left;
}

#progressBar {
    width: 90%;
    margin: 10px auto;
    height: 22px;
    background-color: #fff;
    border:1px solid #ddd;
}
#progressBar div {
  height: 100%;
  text-align: right;
  padding: 0;    /* remove padding */
  line-height: 22px;
  width: 0;
  background-color: #CBEA00;
  box-sizing: border-box;
  overflow: visible;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.jqueryscript.net/demo/Minimal-jQuery-Any-Date-Countdown-Timer-Plugin-countdown/dest/jquery.countdown.js"></script>

  <div id="progressBar">
      <div></div>
  </div>
0 голосов
/ 09 октября 2018

Я добавлю это как ответ вместо комментария:

вместо вычисления в сторону увеличения, вычтите прогресс из общей суммы:

var totalTime = 100;
var currentTime = 15;
var timeRemaining = totalTime - currentTime;
var progressPCT = (currentTime / totalTime ) * 100;
var remaningProgressPCT = 100 - progressPCT; 
console.log("Time Remaining: ", timeRemaining);
console.log("Progress Bar Fill: ", remainingProgressPCT);

, затем поместите переменную remaningProgressPCT в качестве прогресса натвой бар?

...