在这个 jQuery 开关中,我试图使当前单击的按钮在单击另一个按钮时返回到其原始状态。也像关闭按钮一样,在加载页面时首先自动单击。我已经尝试了很多代码,但似乎无法让它工作。
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Toggleswitch</title>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<div class="switchcontainer">
<button id="darkmodeon">ON</button>
<button id="darkmodeoff">OFF</button>
</div>
</body>
</html>
CSS:
body{
background-color: black;
}
.switchcontainer{
background-color: white;
display: flex;
justify-content: space-between;
border-radius: 50px;
width: 125px;
padding: 5px;
}
button{
width:50px;
height: 50px;
border: none;
border-radius: 50px;
background-color: #d8d8d8;
color: #777777;
font-family: 'calibri light';
font-size: 17px;
font-weight: bold;
}
jQuery:
$(document).ready(function(){
var darkon = '#darkmodeon';
var darkoff = '#darkmodeoff';
$(darkon).click(function(){
$(this).css({
"background-color": "#85c452",
"color": "white",
"transition": "all 0.2s ease"
});
});
$(darkoff).click(function(){
$(this).css({
"background-color": "#85c452",
"color": "white",
"transition": "all 0.2s ease"
});
$(this).off('click',darkon);
});
});
最佳答案
您可以使用类和 Jquery 轻松完成。
为您的“开启”状态创建一个新类。
.on {
background-color: #85c452;
color: white;
transition: all 0.2s ease;
}
然后更改您的点击处理程序以打开和关闭此类,而不是设置特定的 CSS 样式。
$(document).ready(function(){
var darkon = '#darkmodeon';
var darkoff = '#darkmodeoff';
$(darkon).click(function(){
$(this).addClass("on");
$(darkoff).removeClass("on");
});
$(darkoff).click(function(){
$(this).addClass("on");
$(darkon).removeClass("on");
});
});
关于javascript - 单击其他按钮时如何删除 jQuery .css()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44895002/