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

点击按钮后修改div元素onhover背景色为蓝色的实现问题

Fixing the Hover Color Change Without Altering Normal State

The issue with your current code is twofold:

  • When you hover a .box, it applies an inline background style to all .box elements, not just the one being hovered.
  • This inline style doesn't get removed when the mouse leaves, so the normal state of the div stays blue after the first hover.

Instead of manipulating inline styles directly, we can use CSS classes to control the hover state cleanly. Here's the corrected approach:

Updated CSS

We'll add a special class that overrides the hover color when applied:

.box {
  /* Optional: Set a default background if you want one */
  background: #fff;
  padding: 20px;
  margin-top: 10px;
}

.box:hover {
  background: red;
}

/* This class will override the default hover color */
.box.hover-blue:hover {
  background: blue;
}

Updated JavaScript

Instead of binding mouseover/mouseout events, we just toggle the custom class on button click:

$(document).on("click", "button", function() {
  // Toggle the class to switch between red and blue hover
  $(".box").toggleClass("hover-blue");
  
  // If you only want to set it to blue once (no toggle), use:
  // $(".box").addClass("hover-blue");
});

Updated HTML (no changes needed, included for completeness)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button>Change hover color</button>
<hr/>
<div class="box">Hello</div>

Why this works:

  • CSS classes keep all styling logic in your stylesheet, making it easier to maintain.
  • The .hover-blue class only affects the hover state (thanks to the :hover pseudo-class), so the normal state of the div remains unchanged.
  • Using toggleClass lets users click the button again to revert to the original red hover color (if you don't need this functionality, use addClass instead).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:55:18