用javascript改变css浮动属性



我想为我的网站做一个暗模式按钮。我的想法是使用事件点击来改变我的按钮开关的侧面从左到右和从右到左。它工作在我的第一次点击,它从左切换到右(从关闭到打开)。但是当我试着把它换回来的时候,什么也没发生。这是我的代码

const buttonmode = document.querySelector("#darkmode");
const switchmode = document.querySelector("#darkswitch");
buttonmode.addEventListener("click",(e) =>{
e.preventDefault();
if(switchmode.style.float="left"){
switchmode.style.float="right";
} 
else if(switchmode.style.float="right"){

switchmode.style.float="left";
}
});
heres my css
button span{
display: block;
background: #999;
height: 26px;
width: 26px;
border-radius: 50%;
margin-left: 2px;
float: left;
}

我建议使用classList.toggle

const themeSwitcher = document.getElementById("themeSwitcher");
themeSwitcher.addEventListener("click", function () {
this.classList.toggle("dark");
});
#themeSwitcher {
width: 70px;
height: 30px;
border-radius: 50px;
background-color: #ffffff;
border: 2px solid #252525;
}
#toggler {
float: left;
width: 30px;
height: 30px;
background-color: #000000;
border-radius: 50%;
}
.dark #toggler {
float: right;
}
<div id="themeSwitcher">
<div id="toggler"></div>
</div>

您的问题是您在函数之外定义switchmode变量并在函数中重用它。无论DOM何时更新,变量都不会按照预期进行更新。对于函数中的下一次更新,您应该再次获得switchmode

你这里也有一个小问题

if(switchmode.style.float="left")

在if-else条件下应该是===而不是=

const buttonmode = document.querySelector("#darkmode");
buttonmode.addEventListener("click",(e) =>{
e.preventDefault();
const switchmode = document.querySelector("#darkswitch"); //move it here
if(switchmode.style.float==="left"){
switchmode.style.float="right";
} 
else if(switchmode.style.float==="right"){

switchmode.style.float="left";
}
});

在条件语句中,为了检查当前float的值是什么,您需要使用==而不仅仅是=

const buttonmode = document.querySelector("#darkmode");
const switchmode = document.querySelector("#darkswitch");
buttonmode.addEventListener("click",(e) =>{
e.preventDefault();
if(switchmode.style.float == "left") {
switchmode.style.float="right";
} else {
switchmode.style.float="left";
}
});
#darkswitch {
width:50px;
height:50px;
background:black;
}
<button id="darkmode">Dark Mode</button>
<div id="darkswitch"></div>

最新更新