我在SO中使用上一个问题来帮助我完成此“ open-in-new-window” javascript函数:

Copy div And his style to new window

因此,我的目标是在新窗口中打开一个内联div,然后能够打印新窗口(我要在新窗口中打开的div是优惠券)。

我已经完成了div的样式设置(看起来像优惠券)并设置了javascript,以便div的确在新窗口中打开,但是

1)...我无法获取样式表链接到新窗口,

2)...而且,我无法打印新窗口(相反,当我单击以打印新窗口时,什么也没有发生-但是,当我关闭新窗口时,将出现打印对话框。

这是到目前为止我使用的代码,非常感谢您的帮助:

$('#printCoupon').bind('click', function () {
    var printContents = new $("#coupon").clone();
    var myWindow = window.open("", "popup", "width=600,height=380,scrollbars=yes,resizable=yes," +
"toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0");
    var doc = myWindow.document;
    doc.open();
$(printContents).find("#printCoupon").remove();
    doc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
    doc.write("<html>");
    doc.write("<head>");
    doc.write("<link href='http://[link-to-css]/css/coupon.css' rel='stylesheet' type='text/css' />"); // your css file comes here.
    doc.write("</head>");
    doc.write("<body>");
    doc.write($(printContents).html());
    doc.write("</body>");
    doc.write("</html>");
});


和我的HTML:

<div id="couponWrap">
    <div id="coupon">
        <h3>Coupon Title</h3>
        <p>Present this coupon and receive $10 off labor on your first service visit and 2% loyalty points on you next visit.</p>
    </div>
        <a href="javascript:;" id="printCoupon">Click to print this coupon.</a>
</div>


谢谢,
辛迪

最佳答案

就编写而言,请尝试以下操作(已删除doc.open()和已删除popup参数):

$('#printCoupon').bind('click', function () {
    var printContents = new $("#coupon").clone();
    var myWindow = window.open("", "", "width=600,height=380,scrollbars=yes,resizable=yes," +
"toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0");
    var doc = myWindow.document;
$(printContents).find("#printCoupon").remove();
    doc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
    doc.write("<html>");
    doc.write("<head>");
    doc.write("<link href='http://[link-to-css]/css/coupon.css' rel='stylesheet' type='text/css' />"); // your css file comes here.
    doc.write("</head>");
    doc.write("<body>");
    doc.write($(printContents).html());
    doc.write("</body>");
    doc.write("</html>");
});

关于javascript - 使用JavaScript在新窗口中打开内联div,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22309363/

10-11 08:12