如何在两个日期之间移动进度条 slider/pointer?

How to move progress bar slider/pointer between two dates?

我用 html、css 和 javascript/jQuery 开发了进度条。
现在我正在尝试移动垂直线滑块/指针图像,因为日子接近结束日期。滑块/指针只能在开始日期和结束日期之间移动。

这是我目前试过的 fiddle link:
Updated JSFiddle link

javascript 有问题。下面是代码:

var start = new Date(2021, 3, 20), 
  end = new Date(2021, 4, 20), 
  today = new Date(), 
  p = Math.round(((today - start) / (end - start)) * 100) + '%';
// Update the progress bar
$('img').css("margin-left", p).after().append(p);

滑块/指针也在容器外移动。希望能得到各位专家的帮助:)

谢谢,
里查

由于 today 可以在这两个日期之外,因此您需要将 p 限制为 0-100。 另外,你的图片每边都有很宽的边框,显示在区域之外。

var start = new Date(2021, 3, 20), 
    end = new Date(2021, 4, 20), 
    today = new Date(),
    p =  Math.max(0, Math.min(100, Math.round(((today - start) / (end - start)) * 100))) + "%";

// Update the progress bar
$('.indicator').css("width", p).find("span").text(p);

// update start/end dates
$('.ldate').text(start.getDate() + "/" + (start.getMonth()+1) + "/" + start.getFullYear());
$('.rdate').text(end.getDate() + "/" + (end.getMonth()+1) + "/" + end.getFullYear());

//demo
p = Math.max(0, Math.min(100, Math.round(((today - start) / (end - start)) * 100)));
!function slider()
{
  $('.indicator').css("width", p + "%").find("span").text(p + "%");
  if (++p > 100)
    p = 0;
  
  setTimeout(slider, 200);
}()
.container {
  background: grey;
  padding: 10px;
  display: block;
  position: relative;
}
.container .pbcolor {
  display: flex;
  flex-basis: 100%;
/*  padding: 23px 10px; */
  background: #ffedc4;
}
.container .mdate {
  font-weight: bold;
  display: flex;
  flex-basis: 100%;
  margin-top: 10px;
  color: #fcfcfc;
}
.container .mdate .ldate {
  display: inline-block;
  flex-basis: 50%;
}
.container .mdate .rdate {
  display: inline-block;
  text-align: right;
  flex-basis: 50%;
}

/* added */
.container .indicator {
  min-width: 2px;
  top: 0px;
/*  border: 1px solid black; */
  overflow: hidden;

  background-image: url('https://www.linkpicture.com/q/vlt_1_1.png');
  background-repeat: no-repeat;
  background-size: contain;
  background-position: right;

  text-align: center;
}
.pbcolor
{
  height: 65px;
  line-height: 65px;
}
.indicator > img
{
  height: 65px;
  float: right;
}

.ltext
{
  float: left;
  position: absolute;
}
.rtext
{
  float: right;
  position: absolute;
  right: 10px; /* same as padding in .container */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
    <div class="pbcolor">
      <div class="ltext">Text on left</div>
      <div class="indicator">
<!--        <img src="https://www.linkpicture.com/q/vlt_1_1.png"> -->
        <span></span>
      </div>
      <div class="rtext">Text on right</div>
    </div>
    <div class="mdate">
       <span class="ldate">20/4/2021</span><span class="rdate">20/5/2021</span>
    </div>
</div>

如果图像的宽度为 2 像素,则它会正确显示,因为它显示的“不正确”尺寸远离右边缘,并且在 25% 之前它显示的尺寸错误。