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

JavaScript实现Div交替变色及鼠标移出恢复背景色问题

问题根源分析

你遇到的核心问题是全局变量oldBackColor被共享覆盖:当多个带有rowstriped类的行触发鼠标事件时,后续行的原始背景色会覆盖这个全局变量,导致之前的行在鼠标移出时,恢复的不是自己原本的颜色,而是最后一次触发事件的行的颜色。


解决方案

下面提供几种不同的实现思路,从修复原有代码到更优雅的优化方案:

方案1:修复原有代码(保留内联事件)

把全局变量替换为元素自身的data属性,为每个行单独存储它的原始背景色,避免全局污染:

$(document).ready(function () {
    $(".row.rowstriped:even").css("background-color", "lightGray");
});

function DoRowGold(el) {
    // 仅在首次移入时存储原始背景色,避免重复覆盖
    if (!$(el).data('originalBg')) {
        $(el).data('originalBg', $(el).css('background-color'));
    }
    $(el).css('background-color', '#FFD700');
}

function DoRowNormal(el) {
    // 从当前元素的data属性中取出专属的原始颜色
    const originalBg = $(el).data('originalBg');
    if (originalBg) {
        $(el).css('background-color', originalBg);
    }
}

HTML部分保持不变(你提到实际代码有Razor生成的id,这里没问题):

<div id="someid" class="row rowstriped" onmouseover="DoRowGold(this)" onmouseout="DoRowNormal(this)">
    <!-- 行内容 -->
</div>

方案2:用jQuery事件绑定替代内联事件(更优雅)

去掉HTML中的内联事件,统一用jQuery绑定事件,代码更易维护:

$(document).ready(function () {
    // 初始化交替灰色背景
    $(".row.rowstriped:even").css("background-color", "lightGray");

    // 绑定hover事件(包含移入和移出逻辑)
    $(".row.rowstriped").hover(
        // 鼠标移入时的逻辑
        function() {
            if (!$(this).data('originalBg')) {
                $(this).data('originalBg', $(this).css('background-color'));
            }
            $(this).css('background-color', '#FFD700');
        },
        // 鼠标移出时的逻辑
        function() {
            const originalBg = $(this).data('originalBg');
            if (originalBg) {
                $(this).css('background-color', originalBg);
            }
        }
    );
});

对应的HTML简化为:

<div id="someid" class="row rowstriped">
    <!-- 行内容 -->
</div>

方案3:纯CSS实现(最简洁高效)

如果不需要兼容极旧的浏览器,完全可以用CSS实现所有需求,无需JavaScript:

/* 初始化交替灰色背景 */
.rowstriped:nth-child(even) {
    background-color: lightGray;
}

/* 鼠标移入时的金色背景 */
.rowstriped:hover {
    background-color: #FFD700;
}

这种方式的优势:浏览器会自动处理背景色的恢复,代码量最少,性能最优,完全避免了JS的变量管理问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:14:43