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

如何对已隐藏的元素使用jQuery的.hover()方法?

解决#band元素fadeOut后无法触发hover事件的问题

你猜的完全没错!问题的核心就是**fadeOut()会把元素最终设置为display: none**,这时候元素直接从页面布局中消失了,鼠标根本碰不到它,自然触发不了hover事件。下面是具体的修复方案:

核心思路

用fadeTo()代替fadeOut()和fadeIn():

  • fadeTo()只会修改元素的透明度(opacity),不会改变它的display属性,元素会一直保持在页面布局中,这样鼠标就能检测到hover动作。
  • 同时修正hover事件的写法——你现在的代码是直接执行了fadeIn/fadeOut,而不是把函数绑定到hover事件上,这会导致页面加载时就直接执行动画,而非hover时触发。

修改后的完整代码

JavaScript/jQuery部分

function A() { document.body.style.backgroundColor = "#FF1493"; }
function B() { document.body.style.backgroundColor = "#22F822"; }
function C() { document.body.style.backgroundColor = "#888888"; }
function D() { document.body.style.backgroundColor = "#2262FF"; }

$(document).ready(function() {
  // 页面加载后将band透明化,而非隐藏
  $("#band").fadeTo(750, 0);
  
  // 正确绑定hover事件:传入两个函数(鼠标进入/离开)
  $("#band").hover(
    function() {
      $(this).fadeTo(750, 1); // 鼠标进入时显示(透明度1)
    },
    function() {
      $(this).fadeTo(750, 0); // 鼠标离开时透明(透明度0)
    }
  );
});

CSS部分(补充必要样式)

/*Basic Format*/
#band {
  border: 1px solid black;
  background: #959595;
  width: 100%;
  top: 0;
  position: fixed; /* 固定在顶部,滚动页面也能hover到 */
  height: 40px; /* 给元素一个固定高度,确保透明时能被鼠标检测到 */
  transition: opacity 0.75s; /* 可选:和fadeTo动画保持一致的过渡效果 */
}
#colors {
  left: 0;
  width: 15%;
  background-color: grey;
}
.buttoncolor {
  cursor: pointer;
  border: 1px solid white;
  margin: 10px;
  width: 20px;
  height: 20px;
}
#buttonA {
  background-color: #FF1493;
}
#buttonB {
  background-color: #22F822;
}
#buttonC {
  background-color: #888888;
}
#buttonD {
  background-color: #2262FF;
}

HTML部分(无需修改,保持原样)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="A()">
  <div class="fade" id="band">
    <div id="colors">
      <button type="button" class="buttoncolor" id="buttonA" onclick="A()"></button>
      <button type="button" class="buttoncolor" id="buttonB" onclick="B()"></button>
      <button type="button" class="buttoncolor" id="buttonC" onclick="C()"></button>
      <button type="button" class="buttoncolor" id="buttonD" onclick="D()"></button>
    </div>
  </div>
  <div><h1>TITLE</h1></div>
</body>

额外说明

  1. position: fixed:让#band固定在页面顶部,即使页面滚动,鼠标也能在顶部区域触发hover。如果不需要固定,可以换成position: absolute或者去掉,但要确保元素在页面可视范围内。
  2. 高度设置:透明后的元素没有视觉反馈,给它一个固定高度能让用户明确知道哪里可以hover。
  3. hover事件的正确写法:hover方法需要接收两个函数参数——第一个是鼠标进入时的回调,第二个是鼠标离开时的回调,不能直接传执行后的动画结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:01:25