Функциональное выражение с немедленным вызовом (IIFE) немедленно вызывает функцию. Это просто означает, что функция выполняется сразу после завершения определения.
Три более распространенных формулировки:
// Crockford's preference - parens on the inside
(function() {
console.log('Welcome to the Internet. Please follow me.');
}());
//The OPs example, parentheses on the outside
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
console.log('Welcome to the Internet. Please follow me.');
}();
Если особых значений для возвращаемого значения нет, тогда мы можем написать:
!function(){}(); // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}(); // => NaN
В качестве альтернативы это может быть:
~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();
Вы даже можете написать:
new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required
Незначительные изменения в более ранней версии - проверены на CHROME
function PrintElem(elem)
{
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
mywindow.document.write('<html><head><title>' + document.title + '</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h1>' + document.title + '</h1>');
mywindow.document.write(document.getElementById(elem).innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}
Принятое решение не работает. Chrome печатал пустую страницу, потому что она не загружала изображение вовремя. Этот подход работает:
Изменить: похоже, принятое решение было изменено после моего сообщения. Почему нисходящий? Это решение работает также.
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
w = window.open();
w.document.write(printContents);
w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
return true;
}
Хотя ответ @BC был лучшим для печати одной страницы.
Но для печати нескольких страниц формата A4 в одно и то же время с помощью ctrl + P следующее решение может помочь.
@media print{
html *{
height:0px!important;
width:0px !important;
margin: 0px !important;
padding: 0px !important;
min-height: 0px !important;
line-height: 0px !important;
overflow: visible !important;
visibility: hidden ;
}
/*assing myPagesClass to every div you want to print on single separate A4 page*/
body .myPagesClass {
z-index: 100 !important;
visibility: visible !important;
position: relative !important;
display: block !important;
background-color: lightgray !important;
height: 297mm !important;
width: 211mm !important;
position: relative !important;
padding: 0px;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
orphans: 0!important;
widows: 0!important;
overflow: visible !important;
page-break-after: always;
}
@page{
size: A4;
margin: 0mm ;
orphans: 0!important;
widows: 0!important;
}}
Я думаю, что есть лучшее решение. Сделайте свой div для печати на весь документ, но только при его печати:
@media print {
.myDivToPrint {
background-color: white;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 15px;
font-size: 14px;
line-height: 18px;
}
}
Создайте отдельную таблицу стилей печати, которая скрывает все остальные элементы, кроме содержимого, которое вы хотите распечатать. Отметьте его, используя 'media="print"
при его загрузке:
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
Это позволяет вам иметь совершенно другую таблицу стилей, загруженную для распечаток.
Если вы хотите, чтобы диалоговое окно печати браузера появилось для страницы, вы можете сделать это как это при загрузке с помощью JQuery:
$(function() { window.print(); });
или сработали любое другое событие, которое вы хотите такой как пользователь, нажимая кнопку.
Я думаю, что предлагаемые до сих пор решения имеют следующие недостатки:
Я улучшил решения выше.
Ключевые моменты для заметок:
<script id="print-header" type="text/x-jquery-tmpl">
<html>
<header>
<title>Printing Para {num}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style>
body {
max-width: 300px;
}
</style>
</header>
<body onload="window.print()">
<h2>Printing Para {num} </h2>
<h4>http://math.tools</h4>
</script>
<script id="print-footer" type="text/x-jquery-tmpl">
</body>
</html>
</script>
<script>
$('.printthis').click(function() {
num = $(this).attr("data-id");
w = window.open();
w.document.write(
$("#print-header").html().replace("{num}",num) +
$("#para-" + num).html() +
$("#print-footer").html()
);
w.document.close();
w.focus();
//w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window.
///w.close(); Don't do this otherwise chrome won't work
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a>
<a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a>
<p class="para" id="para-1">
Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p class="para" id="para-2">
Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
Хотя это было сказано @gmcalab, если вы используете jQuery, вы можете использовать мой плагин printElement.
Здесь есть образец и дополнительная информация о плагине здесь .
Использование довольно прямолинейно, просто возьмите элемент с селектором jQuery и напечатайте его:
$("myDiv").printElement();
Надеюсь, что это поможет!
Используя JQuery, просто используйте эту функцию:
<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
}
</script>
Ваша кнопка печати будет выглядеть так:
<button id="print" onclick="printContent('id name of your div');" >Print</button>
Edit: Если у вас есть данные формы, которые вам нужны чтобы сохранить, клон не будет копировать его, поэтому вам просто нужно захватить все данные формы и заменить его после восстановления так:
<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
var enteredtext = $('#text').val();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
$('#text').html(enteredtext);
}
</script>
<textarea id="text"></textarea>
el
, ужасно, тем более, что с помощью jQ. Гораздо лучше просто передать selector
и избавиться от жестко закодированных #
– RozzA
16 May 2018 в 02:13
То же самое, что и лучший ответ, на случай, если вам нужно распечатать изображение, как я:
Если вы хотите распечатать изображение:
function printElem(elem)
{
Popup(jQuery(elem).attr('src'));
}
function Popup(data)
{
var mywindow = window.open('', 'my div', 'height=400,width=600');
mywindow.document.write('<html><head><title>my div</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<img src="'+data+'" />');
mywindow.document.write('</body></html>');
mywindow.print();
mywindow.close();
return true;
}
load
. Без него вы будете печатать пустую страницу, так как изображение не загружается. = & GT; $(popup).load(function(){ popup.focus(); popup.print(); });
– Tim Vermaelen
29 April 2016 в 11:30
Отсюда http://forums.asp.net/t/1261525.aspx
<html>
<head>
<script language="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>
<title>div print</title>
</head>
<body>
//HTML Page
//Other content you wouldn't like to print
<input name="b_print" type="button" class="ipt" onClick="printdiv('div_print');" value=" Print ">
<div id="div_print">
<h1 style="Color:Red">The Div content which you want to print</h1>
</div>
//Other content you wouldn't like to print
//Other content you wouldn't like to print
</body>
</html>
Я создал плагин для решения этого сценария. Я был недоволен плагинами там и решил сделать что-то более обширное / настраиваемое.
Я знаю, что это старый вопрос, но я решил эту проблему w jQuery.
function printContents(id)
{
var contents = $("#"+id).html();
if ($("#printDiv").length == 0)
{
var printDiv = null;
printDiv = document.createElement('div');
printDiv.setAttribute('id','printDiv');
printDiv.setAttribute('class','printable');
$(printDiv).appendTo('body');
}
$("#printDiv").html(contents);
window.print();
$("#printDiv").remove();
}
CSS
@media print {
.non-printable, .fancybox-outer { display: none; }
.printable, #printDiv {
display: block;
font-size: 26pt;
}
}
В Opera попробуйте:
print_win.document.write('</body></html>');
print_win.document.close(); // This bit is important
print_win.print();
print_win.close();
Вот мой плагин jquery print
(function ($) {
$.fn.printme = function () {
return this.each(function () {
var container = $(this);
var hidden_IFrame = $('<iframe></iframe>').attr({
width: '1px',
height: '1px',
display: 'none'
}).appendTo(container);
var myIframe = hidden_IFrame.get(0);
var script_tag = myIframe.contentWindow.document.createElement("script");
script_tag.type = "text/javascript";
script = myIframe.contentWindow.document.createTextNode('function Print(){ window.print(); }');
script_tag.appendChild(script);
myIframe.contentWindow.document.body.innerHTML = container.html();
myIframe.contentWindow.document.body.appendChild(script_tag);
myIframe.contentWindow.Print();
hidden_IFrame.remove();
});
};
})(jQuery);
Вот решение IFrame, которое работает для IE и Chrome:
function printHTML(htmlString) {
var newIframe = document.createElement('iframe');
newIframe.width = '1px';
newIframe.height = '1px';
newIframe.src = 'about:blank';
// for IE wait for the IFrame to load so we can access contentWindow.document.body
newIframe.onload = function() {
var script_tag = newIframe.contentWindow.document.createElement("script");
script_tag.type = "text/javascript";
var script = newIframe.contentWindow.document.createTextNode('function Print(){ window.focus(); window.print(); }');
script_tag.appendChild(script);
newIframe.contentWindow.document.body.innerHTML = htmlString;
newIframe.contentWindow.document.body.appendChild(script_tag);
// for chrome, a timeout for loading large amounts of content
setTimeout(function() {
newIframe.contentWindow.Print();
newIframe.contentWindow.document.body.removeChild(script_tag);
newIframe.parentElement.removeChild(newIframe);
}, 200);
};
document.body.appendChild(newIframe);
}
Я модифицировал @BillPaetski ответ, чтобы использовать querySelector, добавить необязательный CSS, удалить принудительный тег H1 и сделать заголовок опционально указанным или вытащить из окна. Он также не авто-распечатывается и не подвергает внутренности, поэтому их можно отключить в функции обертки или по своему усмотрению.
Единственными двумя частными vars являются tmpWindow и tmpDoc, хотя я считаю, что доступ к названиям, css и элементу может варьироваться. Следует предположить, что все аргументы функции являются частными.
Код:function PrintElem(elem, title, css) {
var tmpWindow = window.open('', 'PRINT', 'height=400,width=600');
var tmpDoc = tmpWindow.document;
title = title || document.title;
css = css || "";
this.setTitle = function(newTitle) {
title = newTitle || document.title;
};
this.setCSS = function(newCSS) {
css = newCSS || "";
};
this.basicHtml5 = function(innerHTML) {
return '<!doctype html><html>'+(innerHTML || "")+'</html>';
};
this.htmlHead = function(innerHTML) {
return '<head>'+(innerHTML || "")+'</head>';
};
this.htmlTitle = function(title) {
return '<title>'+(title || "")+'</title>';
};
this.styleTag = function(innerHTML) {
return '<style>'+(innerHTML || "")+'</style>';
};
this.htmlBody = function(innerHTML) {
return '<body>'+(innerHTML || "")+'</body>';
};
this.build = function() {
tmpDoc.write(
this.basicHtml5(
this.htmlHead(
this.htmlTitle(title) + this.styleTag(css)
) + this.htmlBody(
document.querySelector(elem).innerHTML
)
)
);
tmpDoc.close(); // necessary for IE >= 10
};
this.print = function() {
tmpWindow.focus(); // necessary for IE >= 10*/
tmpWindow.print();
tmpWindow.close();
};
this.build();
return this;
}
Использование: DOMPrinter = PrintElem('#app-container');
DOMPrinter.print();
<input>
. Как я могу использовать это, включая то, что пользователь набрал?
– Malky.Kid
18 July 2017 в 02:47
<input>
, <select>
, <textarea>
componenttents как их значение времени выполнения. Существуют альтернативы, но это не проблема с этим скриптом, но проблема с работой браузеров и получение innerHTML
свойства документов со входами, холстом и т. Д.
– MrMesees
22 July 2017 в 18:02
.attr('value',)
. Я даже сделал это для textarea (путем добавления) и флажков (.attr('checked',)
). Я извиняюсь i>, если я недостаточно думал о том, что я просил.
– Malky.Kid
23 July 2017 в 23:29
Примечание. Это работает только с сайтами, поддерживающими jQuery
. Это очень просто с этим трюком. Он работал для меня в браузере Google Chrome. Firefox не позволит вам печатать в PDF без плагина.
var jq = document.createElement('script');
jq.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";
document.getElementsByTagName('body')[0].appendChild(jq)
$("#myDivWithStyles").print() // Replace ID with yours
Логика проста. Мы создаем новый тег скрипта и прикрепляем его перед закрывающим тегом body. Мы ввели в HTML расширение для печати jQuery. Измените myDivWithStyles своим собственным идентификатором тега Div. Теперь требуется подготовка готового к печати виртуального окна.
Попробуйте его на любом сайте. Только оговорка иногда ошибочно написана. CSS может привести к отсутствию стилей. Но мы получаем контент большую часть времени.
Создал что-то общее для использования на любом элементе HTML
HTMLElement.prototype.printMe = printMe;
function printMe(query){
var myframe = document.createElement('IFRAME');
myframe.domain = document.domain;
myframe.style.position = "absolute";
myframe.style.top = "-10000px";
document.body.appendChild(myframe);
myframe.contentDocument.write(this.innerHTML) ;
setTimeout(function(){
myframe.focus();
myframe.contentWindow.print();
myframe.parentNode.removeChild(myframe) ;// remove frame
},3000); // wait for images to load inside iframe
window.focus();
}
//usage
document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();
Надеюсь, что это поможет.
Я использовал Bill Paetzke
ответ, чтобы напечатать div, содержащий изображения, но он не работал с google chrome
Мне просто нужно было добавить эту строку myWindow.onload=function(){
, чтобы она работала, и вот полная код
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"> </script>
<script type="text/javascript">
function PrintElem(elem) {
Popup($(elem).html());
}
function Popup(data) {
var myWindow = window.open('', 'my div', 'height=400,width=600');
myWindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
myWindow.document.write('</head><body >');
myWindow.document.write(data);
myWindow.document.write('</body></html>');
myWindow.document.close(); // necessary for IE >= 10
myWindow.onload=function(){ // necessary if the div contain images
myWindow.focus(); // necessary for IE >= 10
myWindow.print();
myWindow.close();
};
}
</script>
</head>
<body>
<div id="myDiv">
This will be printed.
<img src="image.jpg"/>
</div>
<div>
This will not be printed.
</div>
<div id="anotherDiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintElem('#myDiv')" />
</body>
</html>
также, если кому-то просто нужно распечатать div с идентификатором, ему не нужно загружать jquery
, вот чистый код javascript для этого
<html>
<head>
<script type="text/javascript">
function PrintDiv(id) {
var data=document.getElementById(id).innerHTML;
var myWindow = window.open('', 'my div', 'height=400,width=600');
myWindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
myWindow.document.write('</head><body >');
myWindow.document.write(data);
myWindow.document.write('</body></html>');
myWindow.document.close(); // necessary for IE >= 10
myWindow.onload=function(){ // necessary if the div contain images
myWindow.focus(); // necessary for IE >= 10
myWindow.print();
myWindow.close();
};
}
</script>
</head>
<body>
<div id="myDiv">
This will be printed.
<img src="image.jpg"/>
</div>
<div>
This will not be printed.
</div>
<div id="anotherDiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintDiv('myDiv')" />
</body>
</html>
Надеюсь, это может помочь кому-то
Лучший способ сделать это - отправить содержимое div на сервер и открыть новое окно, где сервер может поместить это содержимое в новое окно.
Если это не опция вы можете попытаться использовать язык на стороне клиента, например javascript, чтобы скрыть все на странице, кроме этого div, а затем распечатать страницу ...
Если вы хотите иметь все стили из исходного документа (включая встроенные стили), вы можете использовать этот подход.
Реализация:
class PrintUtil {
static printDiv(elementId) {
let printElement = document.getElementById(elementId);
var printWindow = window.open('', 'PRINT');
printWindow.document.write(document.documentElement.innerHTML);
setTimeout(() => { // Needed for large documents
printWindow.document.body.style.margin = '0 0';
printWindow.document.body.innerHTML = printElement.outerHTML;
printWindow.document.close(); // necessary for IE >= 10
printWindow.focus(); // necessary for IE >= 10*/
printWindow.print();
printWindow.close();
}, 1000)
}
}
function printdiv(printdivname)
{
var headstr = "<html><head><title>Booking Details</title></head><body>";
var footstr = "</body>";
var newstr = document.getElementById(printdivname).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
Это напечатает нужную область div и вернет содержимое, как было. printdivname
- это распечатываемый div.
Приведенный ниже код копирует все соответствующие узлы, которые нацелены на селектор запросов, копирует их стили, как показано на экране, так как многие родительские элементы, используемые для таргетинга на селектора css, будут отсутствовать. Это приводит к небольшому отставанию, если существует множество дочерних узлов с большим количеством стилей.
В идеале у вас будет готовая таблица стилей печати, но это касается случаев использования, где нет листа стилей печати (/ g1)
Если вы скопируете приведенные ниже пункты в консоли браузера на этой странице, он распечатает все фрагменты кода на этой странице.
+function() {
/**
* copied from https://stackoverflow.com/questions/19784064/set-javascript-computed-style-from-one-element-to-another
* @author Adi Darachi https://stackoverflow.com/users/2318881/adi-darachi
*/
var copyComputedStyle = function(from,to){
var computed_style_object = false;
//trying to figure out which style object we need to use depense on the browser support
//so we try until we have one
computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);
//if the browser dose not support both methods we will return null
if(!computed_style_object) return null;
var stylePropertyValid = function(name,value){
//checking that the value is not a undefined
return typeof value !== 'undefined' &&
//checking that the value is not a object
typeof value !== 'object' &&
//checking that the value is not a function
typeof value !== 'function' &&
//checking that we dosent have empty string
value.length > 0 &&
//checking that the property is not int index ( happens on some browser
value != parseInt(value)
};
//we iterating the computed style object and compy the style props and the values
for(property in computed_style_object)
{
//checking if the property and value we get are valid sinse browser have different implementations
if(stylePropertyValid(property,computed_style_object[property]))
{
//applying the style property to the target element
to.style[property] = computed_style_object[property];
}
}
};
// Copy over all relevant styles to preserve styling, work the way down the children tree.
var buildChild = function(masterList, childList) {
for(c=0; c<masterList.length; c++) {
var master = masterList[c];
var child = childList[c];
copyComputedStyle(master, child);
if(master.children && master.children.length > 0) {
buildChild(master.children, child.children);
}
}
}
/** select elements to print with query selector **/
var printSelection = function(querySelector) {
// Create an iframe to make sure everything is clean and ordered.
var iframe = document.createElement('iframe');
// Give it enough dimension so you can visually check when modifying.
iframe.width = document.width;
iframe.height = document.height;
// Add it to the current document to be sure it has the internal objects set up.
document.body.append(iframe);
var nodes = document.querySelectorAll(querySelector);
if(!nodes || nodes.length == 0) {
console.error('Printing Faillure: Nothing to print. Please check your querySelector');
return;
}
for(i=0; i < nodes.length; i++) {
// Get the node you wish to print.
var origNode = nodes[i];
// Clone it and all it's children
var node = origNode.cloneNode(true);
// Copy the base style.
copyComputedStyle(origNode, node);
if(origNode.children && origNode.children.length > 0) {
buildChild(origNode.children, node.children);
}
// Add the styled clone to the iframe. using contentWindow.document since it seems the be the most widely supported version.
iframe.contentWindow.document.body.append(node);
}
// Print the window
iframe.contentWindow.print();
// Give the browser a second to gather the data then remove the iframe.
window.setTimeout(function() {iframe.parentNode.removeChild(iframe)}, 1000);
}
window.printSelection = printSelection;
}();
printSelection('.default.prettyprint.prettyprinted')
mywindow.document.write(data);
Добавьте это:mywindow.document.write('<script type="text/javascript">$(window).load(function() { window.print(); window.close(); });</script>');
И удалите:mywindow.print();
иmywindow.close();
– Fabius 7 November 2015 в 09:58