I'm using a script to prevent my pc to go to sleep when I'm away for 5 minutes.
This does it by playing a little video in the background. However my problem is, I cannot combine 2 functions in a single button so I can have just 1 toggle button and it will on/off based on that?
Here's what I have right now:
var sleep = {
prevent: function() {
if (!this._video) {
this._init();
}
this._video.setAttribute('loop', 'loop');
this._video.play();
},
allow: function() {
if (!this._video) {
return;
}
this._video.removeAttribute('loop');
this._video.pause();
},
_init: function() {
this._video = document.createElement('video');
this._video.setAttribute('width', '10');
this._video.setAttribute('height', '10');
this._video.style.position = 'absolute';
this._video.style.top = '-10px';
this._video.style.left = '-10px';
var source_mp4 = document.createElement('source');
source_mp4.setAttribute('src', 'muted-blank.mp4');
source_mp4.setAttribute('type', 'video/mp4');
this._video.appendChild(source_mp4);
var source_ogg = document.createElement('source');
source_ogg.setAttribute('src', 'muted-blank.ogv');
source_ogg.setAttribute('type', 'video/ogg');
this._video.appendChild(source_ogg);
document.body.appendChild(this._video);
},
_video: null
}
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
<label class="switch">
<input id="onoffbutton" type="checkbox">
<span class="slider round"></span>
</label>
<script>
var count = 0;
$("#onoffbutton").click(function() {
count++;
count % 2 ? $sleep.prevent() : $sleep.allow();
});
function $sleep.prevent () { console.log("on") }
function $sleep.allow () { console.log("off") }
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
question from:
https://stackoverflow.com/questions/65890859/how-to-alternate-function-of-a-toggle-for-on-off 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…