#javascript #html #css
#javascript #HTML #css
Вопрос:
Я столкнулся с препятствием, пытаясь заставить это работать. Я пытаюсь создать переключатель, который включает / выключает действие. Например, когда пользователь включает переключатель, переключатель будет выполнять действие Javascript, когда он находится в положении on, и выключится, когда переключатель переключен в положение off. Это, в конечном счете, моя конечная цель. Что я могу сделать, чтобы это сработало, я делал методом проб и ошибок в течение последних, возможно, 10 дней?? Что я могу сказать? Я полон решимости. Вот код, любая помощь приветствуется! Спасибо всем. <3
<!DOCTYPE>
<html>
<body>
<label class = 'switch'>
<input type = 'checkbox' id = 'yet'>
<span class = 'slider'></span>
</label>
</body>
<style>
.switch {
display: inline-block;
position: absolute;
height: 30px;
width: 60px;
}
#yet{display: none;}
.slider {
top: 1px;
bottom: 0px;
left: 0px;
right: 0px;
position: absolute;
cursor: pointer;
background-color: #D00005;
-webkit-transition: .3s;
border-radius: 25px;
}
.slider:before {
cursor: pointer;
position: absolute;
height: 26px;
width: 26px;
bottom: 2px;
left: 4px;
border-radius: 100%;
content: "";
background-color: #000000;
-webkit-transition: .3s;
}
#yet:checked .slider {
background-color: #16AA03;
}
#yet:checked .slider:before {
-webkit-transform: translateX(26px);
}
</style>
<script>
function myBird() {
document.body.style.backgroundColor = '#000000';
}
function myRed() {
document.body.style.backgroundColor = '#FFFFFF';
}
</script>
</html>
Ответ №1:
Используйте onClick
обработчик событий, проверяя значение this.checked
, чтобы узнать, проверен ли ввод или нет.
HTML:
<input type = 'checkbox' id = 'yet' onclick='handleClick(this)'>
JavaScript:
function handleClick(cb) {
if (cb.checked) {
myBird();
} else {
myRed();
}
}
function myBird() {
document.body.style.backgroundColor = '#000000';
}
function myRed() {
document.body.style.backgroundColor = '#FFFFFF';
}
Все вместе с CSS:
function handleClick(cb) {
if (cb.checked) {
myBird();
} else {
myRed();
}
}
function myBird() {
document.body.style.backgroundColor = '#000000';
}
function myRed() {
document.body.style.backgroundColor = '#FFFFFF';
}
.switch {
display: inline-block;
position: absolute;
height: 30px;
width: 60px;
}
#yet {
display: none;
}
.slider {
top: 1px;
bottom: 0px;
left: 0px;
right: 0px;
position: absolute;
cursor: pointer;
background-color: #D00005;
-webkit-transition: .3s;
border-radius: 25px;
}
.slider:before {
cursor: pointer;
position: absolute;
height: 26px;
width: 26px;
bottom: 2px;
left: 4px;
border-radius: 100%;
content: "";
background-color: #000000;
-webkit-transition: .3s;
}
#yet:checked .slider {
background-color: #16AA03;
}
#yet:checked .slider:before {
-webkit-transform: translateX(26px);
}
<label class = 'switch'>
<input type = 'checkbox' id = 'yet' onclick='handleClick(this)'>
<span class = 'slider'></span>
</label>