web前端之多种方式实现switch滑块功能、动态设置css变量、after伪元素、选择器、has伪类


效果图

switchSkins1


switchSkins2


html+css

html

<div class="s">
    <input type="checkbox" id="si" class="si">
    <label for="si" class="sl"></label>
</div>

style

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background-color: rgb(255, 68, 68);
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

.s {
    width: 80px;
}

.si {
    display: none;
}

.sl {
    display: block;
    width: 80px;
    height: 40px;
    border: 2px solid #cccccc;
    border-radius: 20px;
    padding: 2px;
}

.sl::after {
    display: block;
    content: '';
    width: 50%;
    height: 100%;
    position: relative;
    left: 0;
    background-color: #acacac;
    border-radius: 50%;
    transition: all .5s ease-in;
}

.si:checked+.sl::after {
    left: 50%;
}

body:has(.si:checked) {
    background-color: rgb(68, 68, 255);
}

html+css+JS

html

<div class="s">
    <input type="checkbox" id="si" class="si" onclick="handleSwitch(this)">
    <label for="si" class="sl"></label>
</div>

style

:root {
    --bc: rgb(255, 68, 68);
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background-color: var(--bc);
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

.s {
    width: 80px;
}

.si {
    display: none;
}

.sl {
    display: block;
    width: 80px;
    height: 40px;
    border: 2px solid #cccccc;
    border-radius: 20px;
    padding: 2px;
}

.sl::after {
    display: block;
    content: '';
    width: 50%;
    height: 100%;
    position: relative;
    left: 0;
    background-color: #acacac;
    border-radius: 50%;
    transition: all .5s ease-in;
}

.si:checked+.sl::after {
    left: 50%;
}

function handleSwitch(event) {
    let body = document.querySelector('body');

    if (event.checked) {
        body.style.setProperty('--bc', 'rgb(68, 68, 255)');
    } else {
        body.style.setProperty('--bc', 'rgb(255, 68, 68)');
    }
}

相关推荐

  1. css元素选择

    2024-03-19 20:46:03       34 阅读
  2. 006 CSS常见选择 CSS CSS元素

    2024-03-19 20:46:03       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-19 20:46:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-19 20:46:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-19 20:46:03       82 阅读
  4. Python语言-面向对象

    2024-03-19 20:46:03       91 阅读

热门阅读

  1. LlamaParse: 高效的PDF文件RAG解析工具

    2024-03-19 20:46:03       42 阅读
  2. 强缓存和协商缓存的区别

    2024-03-19 20:46:03       39 阅读
  3. leetcode303--区域和检索

    2024-03-19 20:46:03       41 阅读
  4. React——组件化

    2024-03-19 20:46:03       48 阅读
  5. 2079: [蓝桥杯2023初赛] 冶炼金属

    2024-03-19 20:46:03       41 阅读
  6. 小型路由器,为什么四个端口的IP在一个网段?

    2024-03-19 20:46:03       44 阅读