【问题标题】:Unable To Close Bootstrap Modal With Fade无法使用淡入淡出关闭引导模式
【发布时间】:2019-06-15 15:02:42
【问题描述】:

我正在使用以下代码动态生成模态弹出窗口,但遇到了问题。问题是模态显示正确,但我无法关闭它。我试过data-dismiss="modal".modal("hide") 都没有成功。我检查了按钮点击事件是否被触发,唯一的问题是模式没有关闭。

JS

// Requires jQuery
var dialogHelper = new dialog();

function dialog() {
    /* Bootstrap Modal Dialog
    *  Displays message from parameter
    */
    this.ShowModalDialog = function (message, title, buttons) {
        var dialogMessage = "";
        var dialogTitle = "System Message";
        var dialogButtons = [];

        if (message)
            dialogMessage = message;
        if (title)
            dialogTitle = title;
        if (buttons) {
            dialogButtons = buttons;
        }

        var id = randomString(10);

        jQuery("<div/>", {
            id: id,
            class: "modal fade",
            // href: 'http://google.com',
            //title: title,
            //rel: 'external',
            //text: message
        })
            .attr("tabindex", "-1")
            .attr("role", "dialog")
            .attr("aria-labelledby", id + "Label")
            .attr("aria-hidden", true)
            .attr("data-backdrop", "static")
            .attr("data-keyboard", false)
            .load("/Static/BootstrapDialogTemplate.html", function () {
                $("#" + id + " .modal-title")
                    .attr("id", id + "Label")
                    .text(dialogTitle);
                $("#" + id + " .modal-body").text(dialogMessage);

                var footer = $("#" + id + " .modal-footer");

                dialogButtons.forEach(function (element) {
                    $('<button/>', {
                        text: element.Text,
                        click: function () {
                            if (element.Event) {
                                element.Event();
                            }
                        },
                        class: element.Class
                    })
                        .attr("data-dismiss", "modal")
                        .appendTo(footer);
                });
            })
            .appendTo(document.body)
            .modal("show");
    };
};

/* Automatically destroy modal on close */
$(".modal").on('hidden.bs.modal', function () {
    $(this).data('bs.modal', null);
});

function randomString(length) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = length;
    var randomstring = '';

    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }

    return randomstring;
};

/Static/BootstrapDialogTemplate.html

<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title"></h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
        </div>
    </div>
</div>

示例调用

dialogHelper.ShowModalDialog("Are you sure you want to create this item?", null, [{
        Text: "Yes",
        Event: function () { alert("YES!"); },
        Class: "btn btn-primary"
    }, {
        Text: "No",
        Event: function () { },
        Class: "btn btn-secondary"
    }]);

样本输出

<div id="2tF5r5mecT" class="modal fade show" tabindex="-1" role="dialog" aria-labelledby="2tF5r5mecTLabel" data-backdrop="static" data-keyboard="false" aria-modal="true" style="display: block;">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="2tF5r5mecTLabel">System Message</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">Are you sure you want to create this item?</div>
            <div class="modal-footer">
            <button class="btn btn-primary" data-dismiss="modal">Yes</button><button class="btn btn-secondary" data-dismiss="modal">No</button></div>
        </div>
    </div>
</div>
<div class="modal-backdrop fade show"></div>

通过随机测试,我设法推断出在生成我的模式时删除fade 类可以让我在不进行任何其他更改的情况下关闭它。

来自

jQuery("<div/>", {
        id: id,
        class: "modal fade",
        // href: 'http://google.com',
        //title: title,
        //rel: 'external',
        //text: message
    })

jQuery("<div/>", {
        id: id,
        class: "modal",
        // href: 'http://google.com',
        //title: title,
        //rel: 'external',
        //text: message
    })

我的代码有效,但没有淡入淡出效果。我已经检查了我所有的自定义 CSS 是否有 .fade,但我没有。当问题仍然存在时,浏览器上没有控制台错误。大家有没有遇到过这个问题?我刚刚升级到 JQuery 3.3.1 和 Bootstrap 4.2.1。当没有淡入淡出效果时感觉很奇怪。

普伦克

https://next.plnkr.co/edit/71QNigcwmUombEQ8?open=lib%2Fscript.js&preview

【问题讨论】:

  • 在您的示例中,您应该像这样创建您的 div:jQuery("&lt;div&gt;&lt;/div&gt;") 以确保兼容性。另外,尝试在属性对象中引用"class" 属性。根据文档,这必须被引用,因为 class 是保留字。
  • @jake2389 感谢您的评论,但代码按原样运行。唯一需要担心的是,当我将fade 添加为类时,淡入淡出动画会生效,但即使有data-dismiss="modal"$("#id").modal("hide"),我也无法关闭模式。您可以从示例生成的模式中看到,除了该行为之外没有任何问题。

标签: javascript jquery bootstrap-4 bootstrap-modal


【解决方案1】:

JQuery 的.load() 是异步的。 问题是当.modal("show") 执行时,你的模态内容还没有加载。 如果你修改你的代码以在你传递给.load() 的回调中调用.modal("show"),那么它就可以工作了。

我已经 forked 你的 plunker,所以你可以测试它。我将创建对话框元素并调用.modal("show") 的代码更改为:

jQuery("<div/>", {
    id: id,
    class: "modal fade",
    // href: 'http://google.com',
    //title: title,
    //rel: 'external',
    //text: message
})
    .attr("tabindex", "-1")
    .attr("role", "dialog")
    .attr("aria-labelledby", id + "Label")
    .attr("aria-hidden", true)
    .attr("data-backdrop", "static")
    .attr("data-keyboard", false)
    .load("BootstrapDialogTemplate.html", function () {
        const $this = $(this);
        $this.find(".modal-title")
            .attr("id", id + "Label")
            .text(dialogTitle);
        $this.find(".modal-body", this).text(dialogMessage);

        var footer = $this.find(".modal-footer", this);

        dialogButtons.forEach(function (element) {
            $('<button/>', {
                text: element.Text,
                click: function () {
                    if (element.Event) {
                        element.Event();
                    }
                },
                class: element.Class
            })
                .attr("data-dismiss", "modal")
                .appendTo(footer);
        });
        $this.appendTo(document.body)
            .modal("show");
    });

主要变化是:

  1. 在回调中移动.appendTo(document.body).modal("show");

  2. 添加const $this = $(this),然后使用$this.find()获取要修改的模板片段。

此时,读者会问“好的,但是等等……为什么当 OP 不使用 fade?? 时它会起作用?”

这很复杂。基本的事实是通常 Bootstrap 不是为使用部分组件而设计的。当您调用一个告诉 Bootstrap 使用 DOM 元素作为 Bootstrap 组件的函数时,Bootstrap 关心的所有部分都需要存在。请注意,Bootstrap 不关心的那些位无关紧要。您可以加载一段文本以异步方式放入模态框或图像的正文中,Bootstrap 可以很好地处理它。它不关心这些事情。但是,当您异步加载采用class="modal-dialog"div 时,您会遇到麻烦,因为这是Bootstrap 用来为组件提供行为的DOM 结构的一部分。

在您的原始代码中,当模态创建时,Modal 对象的this._dialog 字段将获得值null,因为在 DOM 树中还没有匹配的元素。当您不使用 fade 时它似乎工作的事实是偶然的。碰巧的是,当您使用fade 时,代码路径会更多地使用this._dialog,因此会因this._dialog 被设置为null 而受到更多干扰。当您不使用fade 时,this._dialog 的使用量会减少,它看起来 工作得很好,但那是运气。我追踪了没有fade 的执行路径,并看到了一些奇怪的事情发生。我预计会遇到问题。

最终,您希望您的对话框组件在调用.modal("show") 之前全部存在于 DOM 中。

【讨论】:

  • 非常有意义!我忽略了.load() 是异步的事实。你的最后一句话说明了一切。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多