点击按钮后修改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 inlinebackgroundstyle to all.boxelements, 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-blueclass only affects the hover state (thanks to the:hoverpseudo-class), so the normal state of the div remains unchanged. - Using
toggleClasslets users click the button again to revert to the original red hover color (if you don't need this functionality, useaddClassinstead).
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

