Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用javascript在打印时仅获取特定于内容的高度和宽度_Javascript_Jquery_Html_Css - Fatal编程技术网

如何使用javascript在打印时仅获取特定于内容的高度和宽度

如何使用javascript在打印时仅获取特定于内容的高度和宽度,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正在开发pos系统,但当我打印我的账单时,它会打印整页,我只希望它只需要特定的宽度和足够的高度就可以覆盖在div中 这是我的密码 <html> <head> <title>div print</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" /> <s

我正在开发pos系统,但当我打印我的账单时,它会打印整页,我只希望它只需要特定的宽度和足够的高度就可以覆盖在div中

这是我的密码

<html>
    <head>
        <title>div print</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js" />
        <script type="text/javascript">
            function printdiv(printpage) {
                var headstr = "<html><head><title></title></head><body>";
                var footstr = "</body>";
                var newstr = document.all.item(printpage).innerHTML;
                var oldstr = document.body.innerHTML;
                document.body.innerHTML = headstr+newstr+footstr;
                window.print();
                document.body.innerHTML = oldstr;
                return false;
            }
        </script>
    </head>
<body>

    <input name="b_print" type="button" class="ipt"   onClick="printdiv('div_print');" value=" Print ">
        <div id="div_print">
            <h1 style="Color:Red">this will print</h1>
        </div>
    </body>
</html>

div打印
函数printdiv(printpage){
var headstr=“”;
var footstr=“”;
var newstr=document.all.item(printpage.innerHTML);
var oldstr=document.body.innerHTML;
document.body.innerHTML=headstr+newstr+footstr;
window.print();
document.body.innerHTML=oldstr;
返回false;
}
这会打印出来

理想的解决方案是在指定尺寸限制的地方使用单独的CSS进行打印。
您可以使用特定于打印的CSS样式表,并隐藏所有内容,但不包括您想要打印的内容。将元素分为两类,一类不会打印,另一类将:

<div class="no-print">Ignore me</div><div class="something-else">Print me! 
 </div>
忽略我打印我!
print类中的元素应保留,而忽略的元素不应打印

<style type="text/css" media="print">
.no-print { display: none; }
</style>

.no打印{显示:无;}

作为警告,请小心使用“document.all.item”,因为如果找到多个元素,它将返回一个元素数组,这些元素可能会导致您的问题

可能的重复会将chartdiv高度设置为200px。“document.getElementById('chartdiv')。style.height='200px'”@lonut NO我只能打印div内容,我的问题是打印时需要整页的高度和宽度,我希望这只需要div高度。明白我的问题吗?没有空白