CSS+Javascript 实现暗黑模式

Subscribe to my newsletter and never miss my upcoming articles

学习的过程中尝试自己去写模版切换的功能,发现写完以后对设计系统颜色的定义理解更深入了。

这里用的方法主要是通过定义 --example 的颜色变亮,以及 .dark 的方式实现页面的两套配色。最后通过 javascript 监听 botton 的点击事件替换css的变亮到 .dark 定义的内容。

body {
    --accent-color:#4E6E0C;
    --accent-color-hovered:#415C0A;
    --background-color:#F0FBDA;
    --text-color:#141D01;
    --text-color-un:#F0FBDA;
    --transform-delay: 1s ;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    height: 100vh;
    margin:0;
    background-color: var(--background-color);
    color: var(--text-color);
    transition:var(--transform-delay) ;
}

body.dark {
    --accent-color:#8FC81E;
    --accent-color-hovered:#B5DE63;
    --background-color:#333333;
    --text-color:#F0FBDA;
    --text-color-un:#141D01;
    --transform-delay:1s;
    --transform-rotation: 0 ;
}

h1,h2,h3,h4,h5,h6{
    margin: 4px;
}

.switchButton {
    background-color: var(--accent-color);
    color: var(--text-color-un);
    padding: 12px 32px;
    border:none;
    outline: none;
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    margin-top: 20px;
    transition: var(--transform-delay);
    transform: scale(1);
}

.switchButton:hover,
.switchButton:focus {
    background-color: var(--accent-color-hovered);
    color: var(--text-color-un);
    outline: none;
    transform:scale(1.1);
}

html 文件


<body id="theme" class="dark">
    <div>
        <h1>👋 Hi, I'm Chenli</h1>
        <h3>
            Digital product designer based in Beijing, currently focused on
            cloud
            computing.
        </h3>
        <p>
            I craft strategy-based products by asking the right questions and understanding the problem. I strive in
            achieving a positive impact on any company or product I am working on.
        </p>
        <p>
            Email:chenlicool@foxmail.com
        </p>

        <button type=" button" class="switchButton">
            点击切换模版
        </button>

    </div>
    </div>

    <script src="src/switchtheme.js"></script>
</body>

Javascript 文件

let theme = document.getElementById('theme');

theme.addEventListener('click', () => {
    document.body.classList.toggle('dark')
});

No Comments Yet