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

jQuery开发Simon色彩游戏:div点击事件禁用与启用问题

解决Simon游戏中禁用div点击事件的问题

问题根源

disabled是HTML表单元素(如<button>、<input>)的专属属性,<div>不属于表单控件,所以无论用.prop('disabled', true)还是.attr('disabled', 'disabled')都无法阻止它的点击事件。

可行解决方案

方案1:用标志变量控制点击逻辑

全局定义一个开关变量,点击事件触发时先判断变量状态,决定是否执行后续逻辑:

// 全局定义游戏激活状态开关
let isGameActive = false;

// 游戏启动时(比如nextSequence函数内)开启开关
function nextSequence() {
  isGameActive = true;
  // 你的原有游戏逻辑...
}

// 修改点击事件监听
allButtons.click(function() {
  // 游戏未激活时直接终止逻辑
  if (!isGameActive) return;

  const userChosenColour = this.id;
  userClickedPattern.push(userChosenColour);
  const userButton = $(`#${this.id}`);

  userButton.fadeTo(100, 0.1, function() { $(this).fadeTo(500, 1.0); });
  makeSound(this.id)

  if (checkAnswer(userClickedPattern.length)) {
    if (userClickedPattern.length === gamePattern.length) {
      title.text('Success')
      setTimeout(function() {nextSequence()}, 1000);
    }
    return true;
  } else {
    title.text('Wrong');
    makeSound('wrong');
    flashBackground();
    // 错误时关闭开关,禁用点击
    isGameActive = false;
    setTimeout(function() {resetGame()}, 500);
    return false;
  }
});

// 重置游戏时根据需求调整开关状态
function resetGame() {
  // 你的原有重置逻辑...
  isGameActive = false; // 若需重新启动游戏,可在启动时再设为true
}

方案2:移除/重新绑定点击事件

把点击逻辑抽成独立函数,需要禁用时移除监听,恢复时重新绑定:

// 抽离点击处理逻辑为独立函数
function handleButtonClick() {
  const userChosenColour = this.id;
  userClickedPattern.push(userChosenColour);
  const userButton = $(`#${this.id}`);

  userButton.fadeTo(100, 0.1, function() { $(this).fadeTo(500, 1.0); });
  makeSound(this.id)

  if (checkAnswer(userClickedPattern.length)) {
    if (userClickedPattern.length === gamePattern.length) {
      title.text('Success')
      setTimeout(function() {nextSequence()}, 1000);
    }
    return true;
  } else {
    title.text('Wrong');
    makeSound('wrong');
    flashBackground();
    // 移除所有按钮的点击监听
    allButtons.off('click');
    setTimeout(function() {resetGame()}, 500);
    return false;
  }
}

// 初始绑定点击事件
allButtons.click(handleButtonClick);

// 重置游戏时重新绑定点击事件
function resetGame() {
  // 你的原有重置逻辑...
  allButtons.click(handleButtonClick);
}

方案3:用CSS pointer-events禁用点击

通过添加CSS类禁止点击,同时可搭配样式直观反馈状态:

/* 定义禁用状态的CSS类 */
.btn-disabled {
  pointer-events: none;
  opacity: 0.5; /* 可选:让按钮变灰,提示不可点击 */
  cursor: not-allowed; /* 可选:鼠标悬停时显示禁止图标 */
}

在JS中通过添加/移除类控制点击权限:

// 错误处理逻辑中添加禁用类
else {
  title.text('Wrong');
  makeSound('wrong');
  flashBackground();
  allButtons.addClass('btn-disabled');
  setTimeout(function() {
    resetGame();
    // 重置时移除禁用类,恢复点击
    allButtons.removeClass('btn-disabled');
  }, 500);
  return false;
}

选择建议

  • 追求简单直观选方案3,既能禁用点击又能给用户视觉反馈;
  • 需要精细逻辑控制选方案1,适合游戏状态多变的场景;
  • 需完全移除事件监听选方案2,注意避免重复绑定的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:25:19