在 JavaScript 1.2 中实现点击按钮后按钮自身变色并保持状态

285 阅读1分钟

以下是调整后的代码:

html
コードをコピーする
<!DOCTYPE html>
<html>
<head>
    <title>Toggle Button Color</title>
    <style>
        /* 默认按钮样式 */
        .button-size {
            width: 100px;
            height: 50px;
            background-color: lightgray;
            color: black;
            border: none;
            font-size: 16px;
            cursor: pointer;
            margin: 10px;
            transition: all 0.3s ease;
        }

        /* 按下按钮后的样式 */
        .button-size.active {
            background-color: blue; /* 按下按钮后按钮背景颜色 */
            color: red; /* 按下按钮后按钮文本颜色 */
            transform: translateY(2px); /* 模拟按下的效果 */
        }
    </style>
</head>
<body>
    <h2>Toggle Button Color Example</h2>
    <button class="button-size" onclick="toggleColor(this)">Button 1</button>
    <button class="button-size" onclick="toggleColor(this)">Button 2</button>
    <button class="button-size" onclick="toggleColor(this)">Button 3</button>

    <script>
        function toggleColor(button) {
            // 切换 active 类
            button.classList.toggle("active");
        }
    </script>
</body>
</html>

解释

  1. CSS部分

    • .button-size:定义按钮的默认样式,包括宽度、高度、背景颜色、文本颜色、无边框、字体大小、指针样式、外边距和过渡效果。
    • .button-size.active:定义按钮按下后的样式,包括改变背景颜色和文本颜色,以及通过 transform: translateY(2px) 模拟按下的效果。
  2. HTML部分

    • 定义多个按钮,每个按钮都有 class="button-size"
    • onclick="toggleColor(this)":在按钮上添加点击事件,将 this 作为参数传递给 toggleColor 函数。this 代表当前被点击的按钮元素。
  3. JavaScript部分

    • toggleColor 函数接受一个参数 button,直接使用该参数来引用被点击的按钮元素,然后使用 classList.toggle 方法切换按钮的 active 类,从而实现样式的切换。

通过以上代码,每次点击按钮时,按钮都会在默认样式和按下样式之间切换,并保持当前状态,直到再次点击按钮切换回去。这种方式可以确保按钮按下后的样式保持不变,直到再次点击。