使用css3实现一个开关灯按钮的动画特效

创建一个开关灯按钮的动画特效,我们可以使用HTML、CSS(包括CSS3的动画和过渡效果)以及JavaScript(如果需要动态交互)。以下是一个简单的示例,演示如何使用CSS3来实现一个开关灯按钮的动画效果。

HTML

首先,我们创建一个简单的HTML结构,包括一个按钮和一个表示灯光的元素。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>开关灯按钮动画</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="light-switch">
        <button id="switchBtn">开关灯</button>
        <div id="lightBulb" class="off"></div>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS (styles.css)

接下来,我们使用CSS来定义按钮和灯光的样式,以及灯光开启和关闭时的动画效果。

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #333;
    color: white;
    font-family: Arial, sans-serif;
}

.light-switch {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
}

#switchBtn {
    margin-bottom: 20px;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s;
}

#switchBtn:hover {
    background-color: #555;
}

#lightBulb {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: transparent;
    border: 2px solid white;
    position: relative;
    transition: background-color 0.5s;
}

#lightBulb.on {
    background-color: yellow;
    box-shadow: 0 0 50px yellow;
}

#lightBulb::before, #lightBulb::after {
    content: '';
    position: absolute;
    background-color: inherit;
    border-radius: 50%;
}

#lightBulb::before {
    width: 70px;
    height: 70px;
    top: 15px;
    left: 15px;
}

#lightBulb::after {
    width: 40px;
    height: 40px;
    top: 30px;
    left: 30px;
}

JavaScript (script.js)

最后,我们使用JavaScript来添加交互功能,使得点击按钮时可以切换灯光的开启和关闭状态。

document.addEventListener('DOMContentLoaded', function() {
    const switchBtn = document.getElementById('switchBtn');
    const lightBulb = document.getElementById('lightBulb');
    let isLightOn = false;
    
    switchBtn.addEventListener('click', function() {
        isLightOn = !isLightOn;
        lightBulb.classList.toggle('on', isLightOn);
        switchBtn.textContent = isLightOn ? '关灯' : '开灯';
    });
});

这个示例中,我们创建了一个简单的开关灯按钮和灯光效果。当点击按钮时,灯光会在开启和关闭状态之间切换,同时按钮的文本也会相应地改变。

posted @ 2024-12-23 09:38  王铁柱6  阅读(136)  评论(0)    收藏  举报