当前位置: 首页 > article >正文

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

MENU

  • 效果图
  • html+css
  • html+css+JS


效果图

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)');
    }
}

http://www.kler.cn/news/274850.html

相关文章:

  • iPhone迎AI大革命:谷歌、OpenAI助苹果重塑智能巅峰
  • 室友打团太吵?一条命令断掉它的WiFi
  • 论文浅尝 | GPT-RE:基于大语言模型针对关系抽取的上下文学习
  • SpringMVC04 实现简单的留言墙功能
  • vue3之声明式和编程式导航
  • 远程安全访问JumpServer:使用cpolar内网穿透搭建固定公网地址
  • [python] ETL 工作流程 Prefect
  • 反射与串扰
  • Gin框架 源码解析
  • 图神经网络实战(5)——常用图数据集
  • 计算机毕业设计-基于python的旅游信息爬取以及数据分析
  • 【web世界探险家】HTML5 探索与实践
  • 【SpringBoot3+MyBatis-Plus】头条新闻项目实现CRUD登录注册
  • webpack5零基础入门-12搭建开发服务器
  • Docker 从0安装 nacos集群
  • Linux文件 profile、bashrc、bash_profile区别
  • vivado 物理优化约束、交互式物理优化
  • 权限维持小结
  • 【回溯、分治、Kadane】算法例题
  • 富格林:揭露黑幕套路安全规避风险