首页 > 解决方案 > 如何在没有任何 html 的情况下使用 vanilla javascript 和 css 制作切换按钮

问题描述

我试图找到一个解决方案,人们总是用 html 或 jQuery 或你有什么解决方案。

所以我做了一个,并认为它可能对其他人有帮助。

标签: javascriptcss

解决方案


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; 
 }


推荐阅读