我尝试进行此切换功能,以便在点击开启按钮并且用户点击时,开启按钮css恢复正常。我还希望在默认情况下设置开关。我也尝试过,但没有运气。
感谢您的帮助!
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="switch-container">
<button id="darkmodeon">ON</button>
<button id="darkmodeoff">OFF</button>
</div>
</body>
</html>
CSS:
body{
background-color: black;
}
.switch-container{
display: flex;
justify-content: space-between;
background-color: white;
border-radius: 50px;
padding: 5px;
width: 135px;
}
#darkmodeon{
width: 50px;
height: 50px;
border-radius: 100%;
border: none;
color: #a5a5a5;
font-family:"calibri light";
font-size: 15px;
font-weight: bold;
background-color: #e8e8e8;
}
#darkmodeoff{
width: 50px;
height: 50px;
border-radius: 100%;
border: none;
color: #a5a5a5;
font-family:"calibri light";
font-size: 15px;
font-weight: bold;
background-color: #e8e8e8;
}
JQUERY:
$(document).ready(function(){
var darkon = "#darkmodeon";
var darkoff = "#darkmodeoff";
$(darkon).click(function(){
$(this).css({
"background-color": "#66e86a",
"color": "white" ,
"transition": "all 0.3s ease"
});
});
$(darkoff).click(function(){
$(this).css({
"background-color": "#66e86a",
"color": "white" ,
"transition": "all 0.3s ease"
});
$(this).unbind('click', darkon);
});
});
答案 0 :(得分:1)
.click(handler)
只是.on('click', handler)
的代理人。要删除以前绑定到任何事件的任何处理程序,请使用:
$(selector).off('eventName', handler)
示例:
var whatever = function(){
// code here
};
$(selector).on('click', whatever); // or $(selector).click(handler);
$(selector).off('click', whatever);
虽然举例说明如何取消绑定,但上面的示例并没有做太多,因为该函数在绑定后立即被解除绑定。通常,您可以根据应用程序的逻辑解除绑定。
例如,如果您想在第一个click
之后取消绑定click
,通常会在绑定函数中使用.off()
:
var whatever = function(){
$(this).off('click', whatever);
// code that only runs on first click.
};
$(selector).on('click', whatever); // or $(selector).click(handler);
至于你的例子,你为什么不在他们的父母那里换班?
$('.parent button').on('click', function(){
$(this).closest('.parent').toggleClass('on');
})
/*.parent button,
.parent.on button:first-child {
display: none;
}
.parent button:first-child,
.parent.on button:last-child {
display: inline;
}*/
/* if you don't want/like the animation, just use the simple `display` switch above */
.parent {
position: relative;
display: inline-block;
}
.parent button {
transition: opacity .2s linear, transform .3s cubic-bezier(.4,0,.2,1);
}
.parent.on button:first-child {
opacity: 0;
transform: translateX(-100%);
}
.parent button:last-child {
position: absolute;
left: 0;
top: 0;
opacity: 0;
transform: translateX(100%)
}
.parent button:first-child,
.parent.on button:last-child {
opacity: 1;
transform: translateX(0)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<button>On</button>
<button>Off</button>
</div>