JavaScript五分钟实现一个开关组件

萌杰尔 -
JavaScript五分钟实现一个开关组件

版权所有:萌杰尔

Copyright: Menger

抄袭可耻

JavaScript五分钟实现一个开关组件各位小伙伴们大家好,我是萌杰尔,好久没有写文了(一直水),今天带着大家来实现一个开关组件吧先不说别的,把代码丢上来

HTML

<switch id="switch">
    <block></block>
</switch>

CSS

:root {
    --switch-color: #3e3e3edd;
    --switch-block-off-color: lightcoral;
    --switch-block-on-color: lightgreen;
}
switch {
    width: 80px;
    height: 34px;
    float: left;
    border-radius: 17px;
    position: relative;
    background-color: var(--switch-color);
}
block {
    width: 40px;
    height: 30px;
    font-size: 10px;
    text-align: center;
    line-height: 30px;
    float: left;
    position: absolute;
    top: 2px;
    left: 2px;
    border-radius: 15px;
    transition: all .1s linear;
    background-color: var(--switch-block-off-color);
}

JavaScript

function $(element) {
    if (typeof element === 'string') {
        var selected = document.querySelectorAll(element);
        if (!selected) {
            console.log('Cannot find element: ' + element);
            return document.createElement('div');
        }
        if (selected.length == 1) {
            return selected[0];
        }
        return selected;
    }
    else {
        return element;
    }
}
var Switch = /** @class */ (function () {
    function Switch(argument) {
        this.element = $(argument.element);
        this.onclick = argument.onclick;
        this.block = this.element.children[0];
        this.text = argument.text;
        this.status = false;
        this.block.innerText = this.text[1];
        this.element.onclick = () => {
            if (this.status) {
                this.status = !this.status;
            }
            else {
                this.status = !this.status;
            }
            this.render();
        };
    }
    Switch.prototype.setStatus = function (status) {
        this.status = status;
        this.render();
    };
    Switch.prototype.render = function () {
        if (this.status) {
            this.block.style.backgroundColor = "var(--switch-block-on-color)";
            this.block.style.left = "38px";
            this.block.innerText = this.text[0];
        }
        else {
            this.block.style.backgroundColor = "var(--switch-block-off-color)";
            this.block.style.left = "2px";
            this.block.innerText = this.text[1];
        }
        this.onclick && this.onclick(this);
    };
    return Switch;
}());

好了,接下来我们讲解代码

HTML首先看HTML,这里就只有一个switch标签和一个block标签,或许你们从来没见过这两个标签,我也没见过,随便用的,你可以用两个div代替,switch是开关主体,block是里面的小圆圈CSS接下来是CSS,这里主要就是switch标签和block标签的样式,你可以根据需求自己更改样式JavaScript

重中之重来啦,JavaScript,先看第1行第16行,这里实现了一个$函数,用于获取元素

 接下来看第17行第34行,这里是开关组件的构造函数,在构造函数一开始,我们拿到配置(option,构造函数中的argument参数)中的element,并通过$函数获取该元素,此时,获取到的应是switch标签。

配置(option)和Switch类中的各项参数属性

element:开关switch元素

onclick:点击事件,点击事件会在render函数结束前被调用

blockblock元素

text:开关组件上显示的文字,用数组表示

status:开关组件当前的状态,用布尔表示

setStatus:设置状态函数

render:渲染函数

接下来我们看第25行第33行,这段代码中为switch元素新增了一个点击事件,其中如果statusfalse()时,status变成true(),反之亦然。

在点击事件结束之前(第32行)会调用render函数重新渲染,那么我们来看一看render函数的具体实现(第39行第51行)。

我们来看第39行第51行,这里首先判断status是否为true(),根据status来更改switch元素中的block元素的背景颜色位置文本

第五十行这里调用了配置中的onclick函数,并将this当作参数传回去。

最后的最后,我们来看第35行第38行setStatus函数,该函数就只有两行,一行是根据参数中的status设置this.status,第二行就是调用render函数来更改开关组件的样式。

使用组件
  <body>
  
      <input type="button" value="点我查看开关状态" id="status">
      
      <switch  id="switch">
        <block></block>
      </switch>
      
      <button id="open-switch" >点我将开关强制打开</button>
      
      <button id="close-switch" >点我将开关强制关闭</button>
      
  </body>
  <script>
  //声明并实例化Switch对象,每次点击switch,会在渲染结束后打印当前状态
    var sth = new Switch({
      element: '#switch',
      text: ['开', '关'],
      onclick: (instance) => {
        console.log(instance.status);
      }
    })
    
    //点击#status元素,switch渲染后弹出前窗台
    $('#status').onclick = () => {
      alert(sth.status)
    }
    
    //点击#open-switch元素,打开switch
    $('#open-switch').onclick = () => {
      sth.setStatus(true);
    }
    
    //点击#close-switch元素,关闭switch
    $('#close-switch').onclick = () => {
      sth.setStatus(false);
    }
  </script>
这就是今天给大家带来的小文章啦,感谢大家阅读。

QQ群: 788951007
我的微信群,欢迎大家加入一起讨论技术
萌杰尔的技术小窝

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

javascript前端html5css3typescript

扩展阅读

加个好友,技术交流

1628738909466805.jpg