首页 > 解决方案 > 如何切换开/关切换功能?

问题描述

我正在使用脚本来防止我的电脑在我离开 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>

标签: javascripthtml

解决方案


推荐阅读