如何根据总小时数制作Time Jquery Slider

时间:2018-01-24 11:17:59

标签: jquery jquery-ui jquery-plugins

我需要时间滑块从04:30到45:30。

我尝试下面的代码

<div id="time-range">
    <p>Time Range: <span class="slider-time">04:30</span> - <span class="slider-time2">45:30</span>

    </p>
    <div class="sliders_step1">
        <div id="slider-range"></div>
    </div>
</div>
$("#slider-range").slider({
    range: true,
    min: 258, /* 04:30 */
    max: 2718, /*45:30*/
    step: 15,
    values: [258, 2718],
    slide: function (e, ui) {
        var hours1 = Math.floor(ui.values[0] / 60);
        var minutes1 = ui.values[0] - (hours1 * 60);

        if (hours1.length == 1) hours1 = '0' + hours1;
        if (minutes1.length == 1) minutes1 = '0' + minutes1;
        if (minutes1 == 0) minutes1 = '00';

        $('.slider-time').html(hours1 + ':' + minutes1);

        var hours2 = Math.floor(ui.values[1] / 60);
        var minutes2 = ui.values[1] - (hours2 * 60);

        if (hours2.length == 1) hours2 = '0' + hours2;
        if (minutes2.length == 1) minutes2 = '0' + minutes2;
        if (minutes2 == 0) minutes2 = '00';

        $('.slider-time2').html(hours2 + ':' + minutes2);
    }
});

此处计算minmax时间为04.30 * 60

但是滑块小时数从min - 04:18max - 45:18开始,我需要min - 04:30max - 45:38

1 个答案:

答案 0 :(得分:0)

这只是因为你的数学错了。 4.5小时是270分钟,而不是258。同样,45.5小时是2730分钟。这是一个工作版本:

$("#slider-range").slider({
  range: true,
  min: 270,
  max: 2730,
  step: 15,
  values: [270, 2730],
  slide: function(e, ui) {
    $('.slider-time').each(function(i) {
      var hours = ("00" + Math.floor(ui.values[i] / 60)).slice(-2);
      var mins = ("00" + (ui.values[i] - (hours * 60))).slice(-2);
      $(this).html(hours + ':' + mins);
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />
<div id="time-range">
  <p>Time Range: <span class="slider-time">04:30</span> - <span class="slider-time">45:30</span></p>
  <div class="sliders_step1">
    <div id="slider-range"></div>
  </div>
</div>

请注意,我还改进了格式化逻辑。