jQuery实现商品区块鼠标悬停仅显示当前元素标题的技术问题
Hey there, I see exactly what's causing the issue—your current script is targeting all .highlight elements globally whenever you hover any .top-section. That's why every title pops up at once instead of just the one for the section you're hovering over. Let's fix this!
The Root Cause
When you use $(".highlight") inside the mouseenter/mouseleave handlers, jQuery selects every element with that class on the entire page. We need to narrow this down to only the .highlight that lives inside the specific .top-section being hovered.
Updated Working Script
Replace your existing script with this:
$(".top-section").on({ mouseenter: function () { // Use $(this) to target the hovered .top-section, then find its child .highlight $(this).find(".highlight").addClass("show").fadeIn(); }, mouseleave: function () { // Same logic here—only target the .highlight inside the hovered section we just left $(this).find('.highlight').removeClass("show").fadeOut(); } });
How This Works
$(this)refers directly to the individual.top-sectionelement that triggered the mouse event (the one you're hovering over, or just finished hovering over)..find(".highlight")searches only within that specific.top-sectionfor the matching element, so we don't touch any other product titles on the page.
Quick CSS Check
Make sure your .highlight class is hidden by default so the fade effects work properly. Here's a basic example:
.highlight { display: none; /* Hides the title by default */ /* Add your own styling: position, background color, padding, etc. */ } /* Optional: If you want to use CSS transitions instead of jQuery's fade methods */ .highlight { opacity: 0; transition: opacity 0.3s ease; } .highlight.show { opacity: 1; }
If you use the CSS transition approach, you can remove the .fadeIn() and .fadeOut() calls from the script since the show class will handle the transition.
内容的提问来源于stack exchange,提问作者user2468312

