【问题标题】:How to keep my custom range/slider follower div perfectly centered with range thumb in Vanilla JavaScript如何让我的自定义范围/滑块跟随 div 与 Vanilla JavaScript 中的范围拇指完美居中
【发布时间】:2016-02-18 19:19:52
【问题描述】:

我花了一些时间来研究一个滑块,它有一个 div 跟随滑块的拇指。我通过为追随者创建一个相对定位的容器(称为#slider-follower-cntnr)来做到这一点。然后我根据范围输入的值调整follower div(#slider-follower)的位置。问题在于,当您在轨道上移动拇指时,跟随器不会完全居中于拇指的位置。我尝试调整#slider-follower-cntnr 的宽度,但我不知道如何找到正确的宽度以使其完全居中。感谢您的帮助。

TL/DR:如何让追随者 div 完全居中于所有范围值的范围输入的拇指?

Heres a codepen. 您可能需要全屏才能看到它在沿范围拉动时偏离中心。

HTML

<div id="slider-cntnr">
  <input type="range" id="frame-slider" oninput="updateFollowerValue(this.value)" />
  <div id="slider-follow-cntnr">
    <div id="slider-follow">
      <div id="slider-val-cntnr">
        <span id="slider-val"></span>
      </div>
    </div>
  </div>
</div>

JS

var follower = document.getElementById('slider-follow');
var follower_val = document.getElementById('slider-val');
var slider = document.getElementById('frame-slider');

var updateFollowerValue = function(val) {
  follower_val.innerHTML = val;
  follower.style.left = (val*1) + '%';
};

updateFollowerValue(slider.value);

CSS

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

#slider-cntnr {
  width: 80%;
  margin: 40px;
  position: relative;
  display: flex;
  flex-direction: column;
  background: orange;
}

#frame-slider {
  width: 100%;
  margin: 0;
}

#slider-follow-cntnr {
  position: relative;
  background-color: blue;
  height: 10px;
  margin: 0 auto;
  width: 98%;
}

#slider-follow {
  background-color: black;
  width: 30px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  margin-left: -15px;
}

#slider-val-cntnr {
  background-color: white;
  width: 25px;
  height: 20px;
}

#slider-val {
  margin-left: 9px;
}

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    解决这个问题的几种方法:

    (1) 在 HTML 中

      <div id="slider-val-cntnr">
        <center>
        <span id="slider-val"></span>
        </center>
      </div>
    

    (2) 在 CSS 中

    #slider-val {
      margin-left: auto;
      margin-right: auto;
    }
    

    (1) HTML 方法可能效果最好,但在整个 HTML 中使用 &lt;center&gt; 标记通常不是最佳做法。

    (2) 这将确保数字永远不会超出它所在的白框的范围。如果您不在乎它绝对居中,并且只想让数字不退出框,那么这是一个合适的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 2019-07-27
      • 2019-03-29
      相关资源
      最近更新 更多