【问题标题】:HTML5 input type range Value Bubbles [closed]HTML5输入类型范围值气泡[关闭]
【发布时间】:2021-01-05 12:40:30
【问题描述】:

我发现了这样的东西:'''https://codepen.io/chriscoyier/pen/eYNQyPe''' 不幸的是,它不适用于表单上的重置按钮。当我点击重置值时没有响应。

【问题讨论】:

  • 无法在 codepen 查看源代码,请在此处创建一个 sn-p,以便任何人都可以更详细地调试
  • 请记住,我们的时间也和您一样有限,因此您需要在此处发布带有文本代码和所有可能调试信息的具体问题。
  • 对不起。下次遇到问题时,我会添加更多信息。 =)

标签: javascript html input range


【解决方案1】:

output 元素没有要重置的默认值,并且位置是使用内联 css 定义的。将初始过程包装成一个函数,重置后调用。

检查这个sn-p:

initRanges();
function initRanges() {
  const allRanges = document.querySelectorAll(".range-wrap");
  allRanges.forEach(wrap => {
    const range = wrap.querySelector(".range");
    const bubble = wrap.querySelector(".bubble");

    range.addEventListener("input", () => {
      setBubble(range, bubble);
    });
    setBubble(range, bubble);
  });
}

const form = document.getElementsByTagName('form')[0];
const reset_btn = document.getElementById('reset_btn');

reset_btn.addEventListener('click', function (e) {
  e.preventDefault();
  form.reset();
  initRanges();
})

function setBubble(range, bubble) {
  const val = range.value;
  const min = range.min ? range.min : 0;
  const max = range.max ? range.max : 100;
  const newVal = Number(((val - min) * 100) / (max - min));
  bubble.innerHTML = val;
  if (bubble.getAttribute('data-defval') === null) {
        bubble.setAttribute('data-defval', val);
  }

  // Sorta magic numbers based on size of the native UI thumb
  bubble.style.left = `calc(${newVal}% + (${8 - newVal * 0.15}px))`;
}
.range-wrap {
  position: relative;
  margin: 0 auto 3rem;
}
.range {
  width: 100%;
}
.bubble {
  background: red;
  color: white;
  padding: 4px 12px;
  position: absolute;
  border-radius: 4px;
  left: 50%;
  transform: translateX(-50%);
}
.bubble::after {
  content: "";
  position: absolute;
  width: 2px;
  height: 2px;
  background: red;
  top: -1px;
  left: 50%;
}

body {
  margin: 2rem;
}
<form>
<div class="range-wrap">
  <input type="range" class="range">
  <output class="bubble"></output>
</div>

<div class="range-wrap">
  <input type="range" class="range" min="20" max="940">
  <output class="bubble"></output>
</div>

<div class="range-wrap" style="width: 75%;">
  <input type="range" class="range" min="50" max="60" step="2">
  <output class="bubble"></output>
</div>

<div class="range-wrap" style="width: 55%;">
  <input type="range" class="range" min="-20" max="20">
  <output class="bubble"></output>
</div>
  <input type="button" id="reset_btn" value="Reset"/>
</form>

【讨论】:

    猜你喜欢
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2015-03-03
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多