解决jQuery hover()效果触发所有div的问题:仅显示当前hover元素对应的description
Hey there! The problem with your current code is that when you use $(".description").show() or .hide(), you're selecting every single element with the .description class on the page. That's why all descriptions pop up or disappear at the same time. Let's adjust this to only target the description inside the rectangle you're actually hovering over.
Option 1: Fix Your Existing jQuery Code
Instead of targeting all .description elements, use $(this).find(".description") to narrow it down to the child element of the hovered rectangle. Here's the updated JavaScript:
function myName(x) { $(x).hover(function() { // Only find the description inside the currently hovered element $(this).find(".description").show(); $(this).addClass("hover"); }, function() { $(this).find(".description").hide(); $(this).removeClass("hover"); }) }; var $projectOneHtml = $(".hTML-1") var $projectTwoHtml = $(".hTML-2") var $projectThreeHtml = $(".hTML-3") myName($projectOneHtml); myName($projectTwoHtml); myName($projectThreeHtml);
Option 2: Simplify Your jQuery (Better Approach)
You don't need to select each rectangle individually. You can bind the hover event directly to all .rectangle elements in one go—this cuts down on redundant code and works for any future .rectangle elements you add:
$(".rectangle").hover(function() { $(this).find(".description").show(); $(this).addClass("hover"); }, function() { $(this).find(".description").hide(); $(this).removeClass("hover"); });
Option 3: No JavaScript Needed (Pure CSS)
For this simple hover effect, you can even skip jQuery entirely and use CSS alone. This is more efficient and keeps your interactive behavior contained in styles:
First, remove the jQuery hover code, then update your CSS:
.description { background-color: white; border: 1px solid white; width: 354px; height: 300px; text-align: center; color: black; font-size: 18px; display: none; } /* Show the description when its parent rectangle is hovered */ .rectangle:hover .description { display: block; } /* Apply your hover styles directly to the rectangle on hover */ .rectangle:hover { /* Add whatever styles were in your .hover class here */ }
This will achieve the exact same result without relying on JavaScript.
内容的提问来源于stack exchange,提问作者Tom

