javascript - 如何切换开/关切换功能?
问题描述
我正在使用脚本来防止我的电脑在我离开 5 分钟时进入睡眠状态。
这是通过在后台播放一个小视频来实现的。但是我的问题是,我不能在一个按钮中组合 2 个功能,所以我只能有 1 个切换按钮,它会根据它打开/关闭吗?
这是我现在所拥有的:
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>
解决方案
推荐阅读
- javascript - 尝试使用角度 9 上传图像 - formData 发送空对象
- python - 带有 ndenumerate 的 Python 2.7 多处理和带有数组/函数参数的函数
- python - 尝试开始训练时出现 UnicodeDecodeError
- unix - 带有变音符号的 Unix 命令从 Robot Framework 执行
- python - 检测 RGB 图像中的模糊度
- ruby-on-rails - 无法加载“pgcrypto”Active Record 适配器
- javascript - 如何在普通 jquery 或 javascript 中翻译 ES6 模板标签?
- java - 我将如何覆盖独立项目中另一个插件提供的任务?摇篮
- c# - 验证 IEnumerable(字符串集合)
- javascript - 如何在 HTML 中将换行符显式显示为“\n”