7月 19, 2017

『html』如何在畫面產生彈跳視窗“Modal”並只列印該部分


這裡教大家如何在html裡面製造出彈跳視窗“Modal”,並列印畫面時只列印該Modal的部分

往往在製作網頁時會用到彈跳視窗Modal,如下圖



而在列印畫面時,若不加以設定則會聯同後面的畫面一起列印出來,因此在這裡提供大家一個方法


首先我們在畫面中先建立一個modal,以下為html:

<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content printMe">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title" id="modal_header">Modal Header</h4>
            </div>
            <div class="modal-body">
                <p>This is a large modal.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" id="btnPrint">Print this page</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>


接著再加入下方的javascript

<script>

    //-----Print Modal Start-----//
    jQuery.fn.extend({
        printElem: function () {
            var cloned = this.clone();
            var printSection = $('#printSection');
            if (printSection.length == 0) {
                printSection = $('<div id="printSection"></div>')
                $('body').append(printSection);
            }
            printSection.append(cloned);
            var toggleBody = $('body *:visible');
            toggleBody.hide();
            $('#printSection, #printSection *').show();
            window.print();
            printSection.remove();
            toggleBody.show();
        }
    });

    $(document).ready(function () {
        $(document).on('click', '#btnPrint', function () {
            $('.printMe').printElem();
        });
    });
    //-----Print Modal End-----//
</script>

透過此方法則可只列印modal中的資料!

David Kung 2017/07/19

沒有留言:

Related Posts Plugin for WordPress, Blogger...