提问者:小点点

如何用普通javascript和css制作切换按钮而不使用任何html


我试图找到一个解决方案,但人们总是给出html或jQuery的解决方案。

所以我做了一个,觉得可能对别人有帮助。


共1个答案

匿名用户

null

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

相关问题