javascript - 如何在没有任何 html 的情况下使用 vanilla javascript 和 css 制作切换按钮
问题描述
我试图找到一个解决方案,人们总是用 html 或 jQuery 或你有什么解决方案。
所以我做了一个,并认为它可能对其他人有帮助。
解决方案
let defaultSetting = "off"
const toggleButton = document.createElement('toggleButton');
toggleButton.onclick = function(){toggleSwitchTransformFunction()};
document.body.appendChild(toggleButton);
const toggleSwitchCircle = document.createElement('toggleSwitchCircle');
toggleButton.appendChild(toggleSwitchCircle);
function toggleSwitchTransformFunction() {
if(defaultSetting == "off"){
defaultSetting = "on"
toggleSwitchCircle.style.transform = "translateX(100%)"
toggleButton.style.background = "black"
// execute code when ON
} else if(defaultSetting == "on"){
defaultSetting = "off"
toggleSwitchCircle.style.transform = "translateX(0%)"
toggleButton.style.background = "white"
// execute code when OFF
}
}
toggleButton{
width: 84px;
min-width: 84px;
display: block;
padding: 4px;
border: 1px black solid;
border-radius: 60px;
transition: 0.5s;
}
toggleSwitchCircle {
display: block;
width: 40px;
height: 40px;
border: 1px black solid;
background-color: white;
border-radius: 50%;
transition: 0.5s;
}
推荐阅读
- css - 每次页面滚动时如何触发动画?
- emacs - 如何重新映射 ido-find-file 中的键?
- python - 在python中按索引将矩阵a中的行添加到矩阵b
- python-3.x - 使用 GPU 和多处理加速对角化
- apache-kafka - Kafka“重试”主题反模式
- mysql - SQL查询中分组后的平均值
- python - 如何使 sklearn.TfidfVectorizer 标记特殊短语?
- jet-ef-provider - VS2017 中的 JetEntityFrameworkProvider 设置
- php - 如何在 curl postfield 中发送 HTML 代码并处理它
- karate - 空手道报告和空手道日志具有带有测试数据的场景名称