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

jQuery 3.6环境下如何检测被.hide()方法隐藏的DOM元素

问题原因
  • 核心问题出在隐藏逻辑的定时器设计:你在// Hide Emoji分支中将$('#Reaction' + val).hide()写在了1500ms的setTimeout回调中,只有等退出动画执行完成后,元素才会被真正设置为display: none。如果你在点击移除按钮后的1.5秒内触发了表情修改逻辑,此时:hidden检测必然返回不符合预期的结果。
  • 次要排查点:确认两个逻辑中取到的val值完全一致,同时检查#Reaction + val对应的元素ID不存在重复、父元素也没有被隐藏的情况。
  • 额外注意:原代码里的$(document).unbind()会清空document上绑定的所有事件,容易影响其他功能,建议替换为指定事件的解绑操作。
修复方案

最稳妥的方式是通过自定义数据标识提前标记元素的隐藏状态,不受动画定时器影响,修改后代码示例如下:

// Change/Add Emoji
// 替换原unbind为指定事件解绑,避免影响其他功能
$(document).off('click', '.messageemoji').on('click', '.messageemoji', function() {
  const val = $(this).closest("table").attr("data-val")
  const emoji = $(this).data("emoji")
  const $reaction = $('#Reaction' + val)

  // 检测逻辑同时判断真实隐藏状态和待隐藏标识
  const isHidden = $reaction.is(':hidden') || $reaction.data('willHide') === true
  if (isHidden) {
    alert('Yes, Element is Hidden');
  } else {
    alert('No, Element is not Hidden');
  }

  // 显示元素同时清除待隐藏标识
  $reaction.data('willHide', false).show();

  // 后续原有逻辑保持不变
  changeemojioutsound.play();
  changeemojioutsound.currentTime = 0;
  $reaction.find("img").addClass("animate__animated animate__zoomOutDown");

  setTimeout(function() {
    changeemojiinsound.play();
    changeemojiinsound.currentTime = 0;
    $reaction.find("img").removeClass("animate__animated animate__zoomOutDown");
    $reaction.find("img").attr("src", 'img/smileyani/' + emoji);
    $reaction.find("img").addClass("animate__animated animate__zoomInUp");
  }, 500)

  setTimeout(function() {
    $reaction.find("img").removeClass("animate__animated animate__zoomInUp");
  }, 1500)
});

// Hide Emoji
$(document).on('click', '.removeemojibtn', function() {
  const val = $(this).attr('data-val');
  const $reaction = $('#Reaction' + val)
  // 点击移除按钮立刻标记待隐藏状态
  $reaction.data('willHide', true)

  console.log(val)

  removeemojioutsound.play();
  removeemojioutsound.currentTime = 0;
  $reaction.find("img").addClass("animate__animated animate__zoomOutRight");

  setTimeout(function() {
    $reaction.find("img").removeClass("animate__animated animate__zoomOutRight animate__zoomOutDown animate__zoomInUp");
    $reaction.hide();
  }, 1500)
});

内容的提问来源于stack exchange,提问作者Stig Kølbæk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:45:00