【问题标题】:Attach current range number directly above HTML range slider thumb在 HTML 范围滑块拇指正上方附加当前范围编号
【发布时间】:2019-05-05 00:01:08
【问题描述】:

是否有一种本机方法可以将当前范围值直接附加到 HTML 范围缩略图的当前位置上方(即,跟踪当前缩略图位置的值)?我目前有一个简单的公式来更新位置,方法是将当前值占总值的百分比乘以滑块的宽度:

updatePosition() {
  const { currentValue, rangeMax, rangeMin } = this.props;
  const sliderWidth = document.getElementsByClassName(className)[0].clientWidth;
  const newPosition = (currentValue - rangeMin) / (rangeMax - rangeMin);
  const updatedPosition = (sliderWidth * newPosition) - 30; // subtracting 30 to help align over slider thumb

  this.setState({ updatedPosition });
}

然后将该"updatedPosition" 值作为div"left" 属性传递,该属性通过内联样式包含该值。

它目前可以工作,但有时会有一点延迟,尤其是在 IE 中,所以我想知道是否有更精确的方法可以获取/更新值的位置。宁愿不使用包。谢谢!

【问题讨论】:

标签: javascript html css reactjs


【解决方案1】:

您应该调整您的函数以使用getBoundingClientRect()。此函数返回一个以窗口坐标为属性的对象。

var pos = element.getBoundingClientRect();
console.log(pos.top)

记录顶部元素边缘的 Y 坐标。

可以在http://javascript.info/coordinates 找到一个很好的参考/解释。

【讨论】:

    【解决方案2】:

    This is the code 我最终使用(不是我的代码)。对于我需要它做的事情来说效果很好。我显然对它稍作改动以使其特定于 React,但除此之外几乎都按原样使用它。

    $('input[type="range"]').on('input', function() {
    
      var control = $(this),
        controlMin = control.attr('min'),
        controlMax = control.attr('max'),
        controlVal = control.val(),
        controlThumbWidth = control.data('thumbwidth');
    
      var range = controlMax - controlMin;
    
      var position = ((controlVal - controlMin) / range) * 100;
      var positionOffset = Math.round(controlThumbWidth * position / 100) - (controlThumbWidth / 2);
      var output = control.next('output');
    
      output
        .css('left', 'calc(' + position + '% - ' + positionOffset + 'px)')
        .text(controlVal);
    
    });
    

    【讨论】:

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