javascript - 如何使用嵌入文本制作切换开关?
问题描述
我正在尝试制作一个在其中嵌入文本的拨动开关。在每月和每年定价之间切换。
这是模拟的图片:
该网站是用 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)}
/>
解决方案
也许它没有实现,查看它看起来不像的文档。
不要绝望,使用一点 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 可能会小得多
推荐阅读
- angular - Angular 6通过id从嵌套数组中获取对象
- php - php 错误:在布尔值上调用成员函数 fetch_assoc()
- python - 使用 diff() 方法减去行
- java - 我被困在Java中的第一个hackerrank挑战中
- javascript - Bootstrap 4 selectpicker基于所选值打开模式
- php - 替换功能不适用于多次替换
- html - 如何在 bootstrap 4 下拉菜单中应用网格系统来塑造它像附加的图像?
- regex - 解开交错的日志(文本)文件
- javascript - 无法在条形图中设置列的宽度
- javascript - 如何使用 JavaScript 将联系人添加到 Dynamics CRM 365