bootbox确认对话框能否通过键盘箭头键切换选中Cancel/OK选项?
Hey there! You’re correct that Bootbox doesn’t include a native configuration for switching between confirm dialog buttons using left/right arrow keys. The official docs don’t cover this because it’s a custom interaction, but it’s easy to implement with a bit of custom JavaScript.
Here’s how to do it:
- After launching your Bootbox dialog, target the OK and Cancel button elements.
- Listen for global
keydownevents to detect left/right arrow presses. - Toggle focus and visual selection state between the buttons when the arrows are pressed.
- Clean up the event listener once the dialog closes to avoid conflicts with other page interactions.
Working Code Example
// Launch the confirm dialog const confirmDialog = bootbox.confirm({ message: "Are you sure you want to proceed?", buttons: { confirm: { label: "OK", className: "btn-primary" }, cancel: { label: "Cancel", className: "btn-secondary" } }, callback: (result) => { // Handle your dialog result here console.log(result ? "User confirmed" : "User canceled"); } }); // Wait for the dialog to fully render before attaching listeners confirmDialog.on("shown.bs.modal", () => { const okBtn = confirmDialog.find(".btn-primary"); const cancelBtn = confirmDialog.find(".btn-secondary"); // Set initial focus to OK button (matches Bootbox's default behavior) okBtn.focus(); okBtn.addClass("focus"); // Listen for arrow key presses $(document).on("keydown", (e) => { // Only handle events if the dialog is visible if (confirmDialog.is(":visible")) { if (e.key === "ArrowLeft") { e.preventDefault(); // Prevent page scrolling cancelBtn.focus(); // Update visual selection state okBtn.removeClass("focus"); cancelBtn.addClass("focus"); } else if (e.key === "ArrowRight") { e.preventDefault(); okBtn.focus(); cancelBtn.removeClass("focus"); okBtn.addClass("focus"); } } }); // Clean up the event listener when the dialog closes confirmDialog.on("hidden.bs.modal", () => { $(document).off("keydown"); }); });
Notes:
- We use Bootstrap modal events (
shown.bs.modalandhidden.bs.modal) to ensure we interact with the dialog at the right time and clean up after ourselves. - Adjust the button class selectors (
.btn-primary,.btn-secondary) to match whatever classes you’re using for your Bootbox buttons. - The
focusclass matches Bootbox’s default visual styling for the active button, so the selection will look consistent with the rest of your dialog.
This implementation will let users toggle between OK and Cancel using left/right arrows, just like you wanted.
内容的提问来源于stack exchange,提问作者Willy David Jr
相关产品推荐
相关产品推荐

