Open a new javascript window(.open) along with its CSS styling

后端 未结 6 495
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 18:50

I\'m trying to get this function to work on the website of a project I\'m working on. The purpose of this function is to only (physically) print the contents of a child div

6条回答
  •  余生分开走
    2020-11-27 18:56

    I do something similiar to the above example but found it doesn't work in all browsers. The following was tested with all the major browsers and works for me. (Remember, some styles can be dependent on parent elements, so if your div is nested inside those elements the styles may not look exactly the same in the print window as on your parent page)

    function printWithCss() {
            //Works with Chome, Firefox, IE, Safari
            //Get the HTML of div
            var title = document.title;
            var divElements = document.getElementById('printme').innerHTML;
            var printWindow = window.open("", "_blank", "");
            //open the window
            printWindow.document.open();
            //write the html to the new window, link to css file
            printWindow.document.write('' + title + '');
            printWindow.document.write(divElements);
            printWindow.document.write('');
            printWindow.document.close();
            printWindow.focus();
            //The Timeout is ONLY to make Safari work, but it still works with FF, IE & Chrome.
            setTimeout(function() {
                printWindow.print();
                printWindow.close();
            }, 100);
        }
    

提交回复
热议问题