JavaScript 打印代码无法正常工作

标签 javascript jquery html css

我的 java 脚本打印代码无法正常工作。我有这个代码是对话框。当用户点击打印按钮时,我正在调用 print() 函数。 当我的打印部分在 Chrome 数据和表格中打开时我面临的问题在预览中无法正常显示。

我试图实现这个 code here

HTML代码:

   <div class="modal-body">
                <div class="" id="mydata">
                    <div id="grid">Some Data</div>
                </div>
            </div>

<button type="button" id="outageSummary_printBtn" class="btnPrint" data-dismiss="modal" onclick="print()>Print</button>

JS 代码:

function print(data, event) {
                event.preventDefault();
                printElement(document.getElementById("grid"));
            };

function printElement (elem) {
                var domClone = elem.cloneNode(true);
                var $printSection = document.getElementById("grid");
                if (!$printSection) {
                    var $printSection = document.createElement("div");
                    $printSection.id = "grid";
                    document.body.appendChild($printSection);
                } else {
                    $printSection.innerHTML = "";
                    $printSection.appendChild(domClone);
                }

                var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
                if (is_chrome == true) {
                    window.print();
                    if (window.stop) {
                        location.reload(); //triggering unload (e.g. reloading the page) makes the print dialog appear
                        window.stop(); //immediately stop reloading
                    }
                } else {
                    window.print();
                }
                return false;
            };

CSS 代码:

@media screen {
    #grid {
        /*display: none;*/
    }
}

@media print {
    body * {
        visibility:hidden;
    }
    #grid, #grid * {
        visibility:visible;
    }
    #grid {
        position:absolute;
        left:0px;
        top:0px;
    }

}

我检查了很多打印功能,但我无法解决这个问题。我相信这与 CSS 或当我添加 Html 元素时有关。

请指导!!

最佳答案

很遗憾,我不能发表评论,但你的意思是它在预览中正确显示,但在网页上却不正确?

(同样从您发布的代码来看,您似乎缺少以下内容 [或按钮上的 onclick 功能]:

document.getElementById("outageSummary_printBtn").onclick = function () { printElement(document.getElementById("grid")); };

抱歉,如果您故意在代码段中遗漏了它)

关于JavaScript 打印代码无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24199363/

相关文章:

javascript - 有人知道这里使用了什么 Javascript 库吗?

html - Bootstrap CSS 到子 div

javascript - 阻止表单提交,直到 recaptcha v3 完成加载

javascript - Javascript 中的 JSON 对象排序

javascript - 未捕获的类型错误 : Cannot read property 'style' of undefined when eventhandling

javascript - 在当前 dom 之前添加 dom,并保持当前 dom 留在视口(viewport)中

javascript - 浏览器 JavaScript 中的 new Date().getTime() 是否总是产生 UTC?

javascript - 如何使用 Debounce Lodash React Native 加快搜索速度

javascript - Bootstrap 日历不显示

jquery - addClass 方法不起作用