首页 > 解决方案 > 如何使用嵌入文本制作切换开关?

问题描述

我正在尝试制作一个在其中嵌入文本的拨动开关。在每月和每年定价之间切换。

这是模拟的图片:

模拟切换图像

该网站是用 React 构建的。我尝试使用React-Toggle Pkg

我可以使用这个包完美地获得样式,但我无法找到在切换中获取文本的好方法。

<Toggle
  name="t-6"
  radius="50px"
  radiusBackground="50px"
  knobRadius="50px"
  width="400px"
  height="55px"
  knobWidth="200px"
  knobHeight="40px"
  onToggle={(e) => console.log("onToggle", e.target)}
/>

标签: javascriptcssreactjs

解决方案


也许它没有实现,查看它看起来不像的文档。

不要绝望,使用一点 DOM(包含组件的行数更少)和 CSS,您可以通过几个无线电输入和随附的标签来实现这一点。

document.querySelectorAll('input[name="pricing"]').forEach(input =>
  input.addEventListener("change", function() {
    document.getElementById('out').innerHTML = `Value: ${this.value}`
  })
)

document.getElementById('out').innerHTML = `Value: monthly`
.pricing-toggle {
  background-color: #3FAED7;
  padding: 14px 5px;
  border-radius: 30px;
  display: inline-block
}

.pricing-toggle [name="pricing"] {
  display: none
}

.pricing-toggle input[type="radio"]+label {
  background-color: #3FAED7;
  color: white;
  padding: 10px 20px;
  border-radius: 30px;
  cursor: pointer;
  user-select: none;
}

.pricing-toggle input[type="radio"]:checked+label {
  background-color: white;
  color: #00008B;
}
<div class="pricing-toggle">
  <input type="radio" id="pricing-toggle-monthly" name="pricing" value="monthly" checked>
  <label class="radio-button" for="pricing-toggle-monthly"> Monthly</label>

  <input type="radio" id="pricing-toggle-annually" name="pricing" value="annually">
  <label class="radio-button" for="pricing-toggle-annually"> Annually</label>
</div>

<div id="out"><div>

不需要示例中的 js,并且使用 scss,CSS 可能会小得多


推荐阅读