为禁用的Bootstrap按钮添加Tooltip失败,请求排查代码问题
问题:禁用状态的Bootstrap按钮无法显示Tooltip
我尝试过类似Stack Overflow线程里的解决方案,但没能实现功能。需要给处于禁用状态的Bootstrap按钮添加Tooltip,告知用户禁用原因。我知道禁用状态的按钮会被CSS阻止鼠标悬停事件触发,也有对应的解决办法,但不清楚自己的代码哪里出错了。
我的代码
JavaScript
// Grab button from DOM let resultsBtn = document.getElementById("get-results-btn"); // if conditional is met, disable button $(resultsBtn).prop("disabled", true); // then, add tooltip $(resultsBtn).attr("data-toggle", "tooltip"); $(resultsBtn).attr("title", "you may only submit this form once"); // add css rules to make tooltip work on disabled button $(resultsBtn).css("pointer-events", "none");
CSS
/* ====================================== */ /* Button styling */ /* ====================================== */ #get-results-btn { /* insert styling rules for color, size, etc. here, plus the following rules: */ cursor: pointer; user-select: none; -webkit-user-select: none; touch-action: manipulation; pointer-events: none; /* Added this based on S/O thread */ } #get-results-btn .btn[disabled] /* I pulled this line from S/O thread, but I don't think the class applies to my code? */
HTML
<button id="get-results-btn" class="btn standard-btn-style"> Get Results </button>
代码错误分析
pointer-events: none设置错误:你给按钮直接添加了这个属性,会让按钮完全不响应任何鼠标事件,包括Tooltip需要的hover触发,完全违背需求。- CSS选择器无效:
#get-results-btn .btn[disabled]是找按钮内部的禁用.btn元素,但你的按钮本身就是目标元素,正确选择器应为#get-results-btn[disabled]。 - 未初始化Bootstrap Tooltip:Bootstrap的Tooltip必须通过JavaScript初始化,仅添加
data-toggle和title属性不会生效。 - 禁用按钮的事件拦截:浏览器默认会阻止禁用按钮的鼠标事件,直接绑定Tooltip到按钮上无法触发。
正确实现方案
方案一:容器包裹按钮(官方推荐)
把Tooltip绑定到按钮的父容器上,绕过禁用按钮的事件拦截。
HTML
<div class="tooltip-wrapper" data-toggle="tooltip" title="you may only submit this form once"> <button id="get-results-btn" class="btn standard-btn-style"> Get Results </button> </div>
JavaScript
// 页面加载完成后初始化所有Tooltip $(function () { $('[data-toggle="tooltip"]').tooltip(); }); // 动态禁用按钮逻辑 let resultsBtn = $('#get-results-btn'); // 条件满足时禁用按钮 resultsBtn.prop("disabled", true); // 若需动态修改提示内容,更新容器的title属性 resultsBtn.parent().attr("title", "you may only submit this form once");
CSS(可选)
.tooltip-wrapper { display: inline-block; /* 避免容器占满整行 */ }
方案二:调整按钮事件属性
开启禁用按钮的鼠标事件,同时保留禁用视觉效果。
HTML
<button id="get-results-btn" class="btn standard-btn-style"> Get Results </button>
JavaScript
$(function () { // 初始化按钮的Tooltip $('#get-results-btn').tooltip(); // 动态禁用并设置提示 let resultsBtn = $('#get-results-btn'); resultsBtn.prop("disabled", true); resultsBtn.attr("title", "you may only submit this form once"); });
CSS
#get-results-btn[disabled] { pointer-events: auto; /* 让禁用按钮响应鼠标事件 */ opacity: 0.65; /* 保留禁用状态的视觉样式 */ cursor: not-allowed; }
内容的提问来源于stack exchange,提问作者Mickey Vershbow
相关产品推荐
相关产品推荐

