Приведенный ниже код копирует все соответствующие узлы, которые нацелены на селектор запросов, копирует их стили, как показано на экране, так как многие родительские элементы, используемые для таргетинга на селектора 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')
'=' является оператором присваивания и будет использоваться для присвоения значений переменным.
$a = 10;
Это означает сохранение 10 в переменную $ a;
$a = 20;
$b = $a;
Приведенный выше пример означает сначала сохранение 20 в переменную $ a, а затем сохранение переменной $ a в $ б. Так как $ a равен 20 и он присваивается $ b, то автоматически $ b также становится 20.
Давайте дошли до "==". Это оператор равенства. Он используется для проверки, являются ли два значения одинаковыми.
$a = 30;
$b = 30;
if ($a == $b){
// do something if both are equal
}
Сравнение использует "==", проверяя, имеет ли $ a то же значение, что и $ b. Это не так точно, как «===» (также сравнивает тип переменной ), но для большинства случаев достаточно «==».
Также есть несколько других операторов, посмотрите документацию: http://php.net/manual/en/language.operators.comparison.php