web-dev-qa-db-ja.com

Twitterを動的にビルドするBootstrap modal

Railsアプリケーションを作成しています。AJAXを介して、Rails partialからモーダルにコンテンツを配置します。

Twitter Bootstrap 2.3.2モーダルでは、リモートキーを使用してajax経由でコンテンツをロードできることをドキュメントで読みました。

http://getbootstrap.com/2.3.2/javascript.html#modals

ただし、これにより、モーダル全体を動的に構築するのではなく、コンテンツを.modal-bodyに挿入することのみが許可されます。

.modal-header.modal-footerを含むモーダル全体をJSで動的に構築する方法はありますか?

次のように、文字列でこれを行うのは非常に不格好なようです:

partial = render_to_string(:partial => 'some-partial').gsub(%{"}, %{'}).gsub(/'/,"\\\\'").gsub("\n", "")
28

更新:

これを投稿してから、エレガントなbootstrap 3モーダルラッパー関数 here が見つかりました。これはdivをhtmlコードに追加する必要がありません。


これを示すコードサンプルを次に示します。使用するには、<body>にdivを追加します(たとえば、ブートストラップの<div class = "container">内に:

<div id="idMyModal"></div>

そして、あなたはそれを介してそれを使用することができます:

var header = "This is my dynamic header";
var content = "This is my dynamic content";
var strSubmitFunc = "applyButtonFunc()";
var btnText = "Just do it!";
doModal('idMyModal', header, content, strSubmitFunc, btnText);

モーダルを閉じるには、以下で定義するhideModalの呼び出しを発行します。

function doModal(placementId, heading, formContent, strSubmitFunc, btnText)
{
    var html =  '<div id="modalWindow" class="modal hide fade in" style="display:none;">';
    html += '<div class="modal-header">';
    html += '<a class="close" data-dismiss="modal">×</a>';
    html += '<h4>'+heading+'</h4>'
    html += '</div>';
    html += '<div class="modal-body">';
    html += '<p>';
    html += formContent;
    html += '</div>';
    html += '<div class="modal-footer">';
    if (btnText!='') {
        html += '<span class="btn btn-success"';
        html += ' onClick="'+strSubmitFunc+'">'+btnText;
        html += '</span>';
    }
    html += '<span class="btn" data-dismiss="modal">';
    html += 'Close';
    html += '</span>'; // close button
    html += '</div>';  // footer
    html += '</div>';  // modalWindow
    $("#"+placementId).html(html);
    $("#modalWindow").modal();
}


function hideModal()
{
    // Using a very general selector - this is because $('#modalDiv').hide
    // will remove the modal window but not the mask
    $('.modal.in').modal('hide');
}
33
Amnon

更新

最近、 bootbox.js につまずきました。これは、bootstrapモーダルを動的に作成し、ユーザーとの対話に反応する専用のライブラリです。以下の方法とは異なりますが、bootboxは関数名ではなくコールバックを受け入れます。以下の機能が行うことを基本的に行うために26kbのライブラリを正当化できないため、私はまだ個人的に使用していません。しかし、誰かがそれを役に立つと思うかもしれません。

2016年8月17日更新

現在、ダイナミックモーダルが必要なほとんどすべてのプロジェクトにブートボックスを使用しています。素晴らしい作品を私はそれを強くお勧めします。

2018/10/1 /更新

Bootboxはまだbootstrap 4を公式にはサポートしていませんが、bootstrap 4サポートに取り組んでいる bootbox v5.x ブランチがあります。 5.0.0 roadmap and Bootbox 5.0 ship list チケットによると、ブランチの準備はかなり整っているように聞こえますが、まだリリースしていません。しかし、それを使用する方法に関するいくつかの指示があります。 免責事項:私はまだv5.xブランチに慣れておらず、その完全性を保証できません。

2019年3月25日更新

Bootstrap 4をサポートするBootbox 5.0がリリースされました。

オリジナルポスト

上記のアンモンの答えからコードを取ります。 bootstrap 3.0の更新

function doModal(placementId, heading, formContent, strSubmitFunc, btnText)
{
    html =  '<div id="modalWindow" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="confirm-modal" aria-hidden="true">';
    html += '<div class="modal-dialog">';
    html += '<div class="modal-content">';
    html += '<div class="modal-header">';
    html += '<a class="close" data-dismiss="modal">×</a>';
    html += '<h4>'+heading+'</h4>'
    html += '</div>';
    html += '<div class="modal-body">';
    html += formContent;
    html += '</div>';
    html += '<div class="modal-footer">';
    if (btnText!='') {
        html += '<span class="btn btn-success"';
        html += ' onClick="'+strSubmitFunc+'">'+btnText;
        html += '</span>';
    }
    html += '<span class="btn" data-dismiss="modal">';
    html += <?php echo "'".__t("Close")."'"; ?>;
    html += '</span>'; // close button
    html += '</div>';  // footer
    html += '</div>';  // content
    html += '</div>';  // dialog
    html += '</div>';  // modalWindow
    $("#"+placementId).html(html);
    $("#modalWindow").modal();
    $("#dynamicModal").modal('show');
}

これは私が自分のニーズに使用することになったものです。また、閉じられたDOMからモーダルを削除するためのイベントハンドラも含まれています。情報モーダルが必要だったので、submit関数とボタンテキスト引数を削除しました。

function doModal(heading, formContent) {
    html =  '<div id="dynamicModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="confirm-modal" aria-hidden="true">';
    html += '<div class="modal-dialog">';
    html += '<div class="modal-content">';
    html += '<div class="modal-header">';
    html += '<a class="close" data-dismiss="modal">×</a>';
    html += '<h4>'+heading+'</h4>'
    html += '</div>';
    html += '<div class="modal-body">';
    html += formContent;
    html += '</div>';
    html += '<div class="modal-footer">';
    html += '<span class="btn btn-primary" data-dismiss="modal">Close</span>';
    html += '</div>';  // content
    html += '</div>';  // dialog
    html += '</div>';  // footer
    html += '</div>';  // modalWindow
    $('body').append(html);
    $("#dynamicModal").modal();
    $("#dynamicModal").modal('show');

    $('#dynamicModal').on('hidden.bs.modal', function (e) {
        $(this).remove();
    });

}
27

DOMを使用して、ボタンと、ボタンがクリックされるとすぐにポップアップするBootstrap=モーダルを作成しました。

また、これらをHTMLページのヘッドセクションに含めます。

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href=      
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script  
src= "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script  
src= "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">     
</script>

このコード全体をJSファイルで記述する必要があります。

//まず、クリックするとBootstrap Modalを表示するボタンを作成します

var button = document.createElement("input");
button.className = 'btn btn-info btn-lg';
button.setAttribute("type", "button");
button.setAttribute("data-toggle", "modal");
button.setAttribute("data-target", "#myModal");              
button.setAttribute("value", "More Information...");
document.getElementsByTagName('body')[0].appendChild(button);   

//モーダルクリエーション:

var div1 = document.createElement('div');
div1.id = 'myModal';
div1.className = 'modal fade';
div1.setAttribute("role", "dialog");     

var innerDiv1m = document.createElement('div');
innerDiv1m.className = 'modal-dialog modal-sm';
div1.appendChild(innerDiv1m);              

var innerDiv2m = document.createElement('div');
innerDiv2m.className = 'modal-content';
innerDiv1m.appendChild(innerDiv2m);

var innerDiv3 = document.createElement('div');
innerDiv3.className = 'modal-header';
innerDiv2m.appendChild(innerDiv3);

var buttonM = document.createElement("button");
buttonM.className = 'close';
buttonM.setAttribute("data-dismiss", "modal");
buttonM.setAttribute("aria-hidden", "true");
buttonM.setAttribute("value", "Close");
innerDiv3.appendChild(buttonM); 

var headerM = document.createElement("H4");
headerM.className = 'modal-title';
innerDiv3.appendChild(headerM);

var innerDiv31 =  document.createElement('div');
innerDiv31.className = 'modal-body';
innerDiv2m.appendChild(innerDiv31);

var para =  document.createElement('p'); 
innerDiv31.appendChild(para);
para.innerHTML = "paragraph";

var innerDiv32 =  document.createElement('div');
innerDiv32.className = 'modal-footer';
innerDiv2m.appendChild(innerDiv32);

var closeButton = document.createElement("input");
closeButton.className = 'btn btn-default';
closeButton.setAttribute("data-dismiss", "modal");
closeButton.setAttribute("type", "button");
closeButton.setAttribute("value", "Close");
innerDiv32.appendChild(closeButton);

document.getElementsByTagName('body')[0].appendChild(div1); 

//したがって、作成されたボタンをクリックすると、モーダルが画面にポップアップします。

5
Khushboo Mulani

受け入れられた答えと非常に似たテーマですが、jQueryプラグインとして記述されています。作業中のツールキットに組み込むためのロジックを探していましたが、これを書いたものを見つけることができませんでした。

以下に多くのコードがありますが、一度書くように設計され、その後簡単に呼び出されるように設計されているため、スポイラーとして、すべての設定が完了したら、次のように簡単に使用できます:

$.fn.alert("utils.js makes this so easy!");

そして、完全な実例として:

https://jsfiddle.net/63zvqeff/

既存の<div />をページ上に置く必要はなく、ネストされたダイアログで動作します。これは、作業中のツールキットから取得したものなので、関連するすべてのビットを含めたので、作業コピー/例を貼り付けます。

(function ($)
{
    $.utils = {
        // http://stackoverflow.com/a/8809472
        createUUID: function ()
        {
            var d = new Date().getTime();
            if (window.performance && typeof window.performance.now === "function")
            {
                d += performance.now(); //use high-precision timer if available
            }
            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c)
            {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        }
    }

    $.fn.dialogue = function (options)
    {
        var defaults = {
            title: "", content: $("<p />"),
            closeIcon: false, id: $.utils.createUUID(), open: function () { }, buttons: []
        };
        var settings = $.extend(true, {}, defaults, options);

        // create the DOM structure
        var $modal = $("<div />").attr("id", settings.id).attr("role", "dialog").addClass("modal fade")
                        .append($("<div />").addClass("modal-dialog")
                            .append($("<div />").addClass("modal-content")
                                .append($("<div />").addClass("modal-header")
                                    .append($("<h4 />").addClass("modal-title").text(settings.title)))
                                .append($("<div />").addClass("modal-body")
                                    .append(settings.content))
                                .append($("<div />").addClass("modal-footer")
                                )
                            )
                        );
        $modal.shown = false;
        $modal.dismiss = function ()
        {
            // loop until its shown
            // this is only because you can do $.fn.alert("utils.js makes this so easy!").dismiss(); in which case it will try to remove it before its finished rendering
            if (!$modal.shown)
            {
                window.setTimeout(function ()
                {
                    $modal.dismiss();
                }, 50);
                return;
            }

            // hide the dialogue
            $modal.modal("hide");
            // remove the blanking
            $modal.prev().remove();
            // remove the dialogue
            $modal.empty().remove();

            $("body").removeClass("modal-open");
        }

        if (settings.closeIcon)
            $modal.find(".modal-header").prepend($("<button />").attr("type", "button").addClass("close").html("&times;").click(function () { $modal.dismiss() }));

        // add the buttons
        var $footer = $modal.find(".modal-footer");
        for(var i=0; i < settings.buttons.length; i++)
        {
            (function (btn)
            {
                $footer.prepend($("<button />").addClass("btn btn-default")
                    .attr("id", btn.id)
                    .attr("type", "button")
                    .text(btn.text)
                    .click(function ()
                    {
                        btn.click($modal)
                    }))
            })(settings.buttons[i]);
        }

        settings.open($modal);

        $modal.on('shown.bs.modal', function (e) {
            $modal.shown = true;
        });
        // show the dialogue
        $modal.modal("show");

        return $modal;
    };
})(jQuery);

次に、基本的なalert()が必要なときのためのヘルパー関数を作成しました

(function ($)
{
    $.fn.alert = function (message)
    {
        return $.fn.dialogue({
            title: "Alert", 
            content: $("<p />").text(message),
            closeIcon: true,
            buttons: [
                { text: "Close", id: $.utils.createUUID(), click: function ($modal) { $modal.dismiss(); } }
            ]
        });
    };

})(jQuery);

それ以外の場合は、コンテンツをjQueryオブジェクトとして構築し、次のようなオブジェクトの形式で渡す必要があります。

{
    title: "", // what ever you want in the title bar
    content: $("<p />"), // any DOM structure you can build as a jQuery object
    closeIcon: false, // does the dialogue have a X in the tilte bar to close it
    id: $.utils.createUUID(), // a reference id 
    open: function () { }, // a function called after the DOM structure is built but BEFORE rendering
    buttons: [ // an array of buttons to include in the footer
        // example "close" button, all buttons get a reference to $modal passed into them 
        // .dismiss() is a function attached to $modal to revert the DOM changes
        { text: "Close", click: function ($modal) { $modal.dismiss(); } }
    ]
};
4
Morvael

私は同じ問題を抱えていました。多くのことを研究した後、最終的にjs関数を作成して、要件に基づいてモーダルを動的に作成しました。この関数を使用すると、次のようなポップアップを1行で作成できます。

puyModal({title:'Test Title',heading:'Heading',message:'This is sample message.'})

または、iframe、ビデオポップアップなど、他の複雑な機能を使用できます。

それを見つける https://github.com/aybhalala/puymodals デモについては、 http://pateladitya.com/puymodals/

0
Adi.P