Bootstrap 5模态框关闭按钮setTimeout启用失败问题求助
Bootstrap 5模态框关闭按钮6秒后未激活的问题解决
我在Bootstrap 5模态框内添加了一个关闭按钮,希望通过setTimeout实现6秒后启用该按钮以关闭模态框,但6秒后按钮仍未激活。
模态框代码
<div class="modal fade" id="videoModal" tabindex="-1" aria-labelledby="videoModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="videoModalLabel">Akacia Electric</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div id="playerModal"></div> </div> <div class="modal-footer"> <button class="btn btn-primary w-100" data-bs-dismiss="modal" aria-label="Close" id="closeBtn" disabled>Close</button> </div> </div> </div> </div>
原jQuery脚本
function openVideoModal() { $('#closeBtn').prop('disabled', true); setTimeout(function() { $('#closeBtn').prop('disabled', true); }, 6000); $('#videoModal').modal('show'); playerModal = new YT.Player('playerModal', { height: '315', width: '100%', videoId: 'DmwyO9GfL2Y', // 这里填你要播放的视频ID playerVars: { 'controls': 1, 'rel': 0, 'showinfo': 0 } }); }
触发模态框的卡片代码
<div class="col"> <div class="card w-75"> <div id="player"></div> <div class="card-body"> <h5 class="card-title">Akacia Electric</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <button class="btn btn-primary w-100" onclick="openVideoModal()">Win points</button> </div> </div>
问题原因及修复方案
问题核心:你的setTimeout回调里,把按钮的disabled属性仍设为true,和初始状态完全一致,等于没做任何启用操作。要激活按钮,必须将disabled改为false。
修正后的jQuery脚本
function openVideoModal() { $('#closeBtn').prop('disabled', true); setTimeout(function() { $('#closeBtn').prop('disabled', false); // 修改为false,启用按钮 }, 6000); $('#videoModal').modal('show'); playerModal = new YT.Player('playerModal', { height: '315', width: '100%', videoId: 'DmwyO9GfL2Y', // 这里填你要播放的视频ID playerVars: { 'controls': 1, 'rel': 0, 'showinfo': 0 } }); }
额外提示
如果想让模态框头部的.btn-close按钮也遵循6秒后才能关闭的规则,需要给它添加ID并设置初始禁用状态:
<button type="button" class="btn-close" id="headerCloseBtn" data-bs-dismiss="modal" aria-label="Close" disabled></button>
然后在setTimeout回调里同时启用它:
setTimeout(function() { $('#closeBtn').prop('disabled', false); $('#headerCloseBtn').prop('disabled', false); }, 6000);
内容的提问来源于stack exchange,提问作者thomasjuan
相关产品推荐
相关产品推荐

