HTML5+CSS3+JS小实例:网站实现一键切换暗色主题

 制作不易 安利给大家前端实用的小实例  cv可直接运行使用  

效果图:

HTML:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网站实现一键切换暗色主题</title>
    <!-- 引入字体图标库 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css">
    <link rel="stylesheet" href="200.css">
</head>
<body>
    <img src="/bd_logo.png" alt="">
    <div class="ipt-box">
        <input type="text">
        <button>百度一下</button>
    </div>
    <div class="switch">
        <i class="fa fa-sun-o"></i>
        <i class="fa fa-moon-o"></i>
    </div>
</body>
</html>

<script src="200.js"></script>

 js:

// 切换按钮
const btn=document.querySelector('.switch');

btn.addEventListener('click',function(){
    let is_dark=document.querySelector('.switch.dark');
    if(!is_dark){
        // 切换为暗色主题
        btn.classList.add('dark');
        let a=document.createElement('style');
        a.id='aa';
        a.innerHTML='html{background-color:#fff;filter:invert(1);}img{filter:invert(1);}';
        document.head.appendChild(a);
    }else{
        // 切换为亮色主题
        btn.classList.remove('dark');
        document.head.querySelector('#aa').remove();
    }
})

css:

*{
    /* 初始化 */
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
/* logo */
img{
    width: 270px;
}
/* 搜索框 */
.ipt-box{
    width: 650px;
    display: flex;
    margin-top: 20px;
    margin-bottom: 200px;
}
.ipt-box input{
    flex: 1;
    border: 2px solid #c4c7ce;
    border-radius: 10px 0 0 10px;
    border-right: none;
}
.ipt-box button{
    width: 108px;
    height: 44px;
    background-color: #4e6ef2;
    color: #fff;
    border: none;
    border-radius: 0 10px 10px 0;
    font-size: 17px;
}
/* 切换按钮 */
.switch{
    border: 1px solid #c4c7ce;
    width: 60px;
    height: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 6px;
    border-radius: 15px;
    cursor: pointer;
    position: fixed;
    top: 15px;
    right: 15px;
}
/* 滑块 */
.switch::before{
    content: '';
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: #4e6ef2;
    position: absolute;
    left: 3px;
    transition: 0.2s ease-out;
}
.switch.dark::before{
    left: 31px;
}
/* 图标 */
.switch .fa{
    font-size: 18px;
    color: #aaa;
}

图片素材:

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耀南.

你的鼓励将是我最最最最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值