You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为多个共享CSS样式的按钮添加:hover悬停效果?

为多个按钮添加:hover悬停效果的解决方案

直接实现方法(无需修改HTML)

如果不想调整现有HTML结构,可以直接给每个按钮类添加:hover伪类,写法如下:

/* 原有共用样式 */
.button-password-simples, .button-password-with-numbers, .button-password-shuffled, .chooser_button {
    cursor: pointer;
    display: inline-block;
    position: relative;
    margin: 0;
    margin-top: 8px;
    padding: 0;
    font-size: 10pt;
    text-align: center;
    width: 90%;
    height: 40px;
    left: 10.5px;
    background-color: #121213c0;
    color: rgba(255, 255, 255, 0.856);
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    border-radius: 3.5px;
    border: none;
    box-shadow: 3px 3px 3px 1px rgb(0 0 0 / 11%);
}

/* hover悬停效果 */
.button-password-simples:hover, .button-password-with-numbers:hover, .button-password-shuffled:hover, .chooser_button:hover {
    /* 示例样式:加深背景色、提高文字不透明度、增强阴影 */
    background-color: #1e1e1fc0;
    color: rgba(255, 255, 255, 1);
    box-shadow: 4px 4px 4px 1px rgb(0 0 0 / 15%);
    /* 可选:添加过渡动画让效果更平滑 */
    transition: all 0.3s ease;
}

优化方案(更易维护)

当前多个类堆叠的写法不利于后续维护,建议给所有按钮添加一个共同的基础类(比如.custom-button),简化CSS结构:

  1. 修改HTML,给每个按钮添加这个共同类:
<button class="custom-button button-password-simples">简易密码</button>
<button class="custom-button button-password-with-numbers">带数字密码</button>
<button class="custom-button button-password-shuffled">随机密码</button>
<button class="custom-button chooser_button">选择按钮</button>
  1. 重构CSS,将共用样式和hover效果绑定到基础类上:
/* 基础按钮样式 */
.custom-button {
    cursor: pointer;
    display: inline-block;
    position: relative;
    margin: 0;
    margin-top: 8px;
    padding: 0;
    font-size: 10pt;
    text-align: center;
    width: 90%;
    height: 40px;
    left: 10.5px;
    background-color: #121213c0;
    color: rgba(255, 255, 255, 0.856);
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    border-radius: 3.5px;
    border: none;
    box-shadow: 3px 3px 3px 1px rgb(0 0 0 / 11%);
    /* 统一添加过渡,让所有状态变化更平滑 */
    transition: all 0.3s ease;
}

/* 通用hover效果 */
.custom-button:hover {
    background-color: #1e1e1fc0;
    color: rgba(255, 255, 255, 1);
    box-shadow: 4px 4px 4px 1px rgb(0 0 0 / 15%);
}

/* 如果某个按钮需要特殊样式,可以单独写 */
.button-password-simples {
    /* 比如这个按钮的专属样式 */
}

这种方式的优势是:后续新增按钮时,只需添加.custom-button类就能自动继承所有基础样式和hover效果,无需重复编写多个选择器,代码更简洁易维护。

内容的提问来源于stack exchange,提问作者Imagem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:15:34