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

解决jQuery hover()效果触发所有div的问题:仅显示当前hover元素对应的description

Fix: Show Only the Hovered Rectangle's 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:59:09