Printing with Style

本文介绍了一种使用CSS样式表来优化网页打印效果的方法,通过创建专门的打印样式表,可以隐藏不需要的内容、调整链接样式,并确保打印输出符合预期。此外,还提供了一个JavaScript示例,用于自动附加页面中的外部链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Printing with Style

By Per S

Introduction

There're a lot of techniques used on the net to create nice looking prints from web pages. Some take a copy of the pages and remove unwanted elements manually, some do it by opening a new print-friendly page using a server side script (ASP, PHP, Perl, ...). I prefer doing it with style :-)

Style

Doing it with style is simple and elegant; you create a separate style sheet with elements suited for print:

  • Set the background to white (background:#ffffff;)
  • Underline links (text-decoration:underline), and maybe color them blue for users with a color printer
  • Hide unwanted parts using display:none;

You attach the style sheet using:

Collapse
<head>
<link rel="stylesheet" type="text/css" href="..." media="print" />
</head>

media="print" (IE 4+, Netscape 6+ and Opera 3.62+) tells the browser to use this only when you print the page.

This is how I attach my print.css.

Collapse
<link rel="stylesheet" type="text/css" 
href="css/print.css" media="print" />

You can test it by printing one of my pages, if you print my Links page you'll also see how I append external links (IE 6+ only):

Collapse
body { 
color : #000000;
background : #ffffff;
font-family : verdana,arial,sans-serif;
font-size : 12pt;
}
h2 {
font-size : 14pt;
}
a {
text-decoration : underline;
color : #0000ff;
}

#logo,#head,#menu,#tail,#printicon, {
display : none;
}

#appendedlinks {
page-break-before: always
}

Append external links

A nice feature is to append all external links in the webpage, to the print document. This is implemented on my pages using the following JavaScript:

Collapse
// 

// IE only: attach eventhandlers.

// They trigger when a user prints a web page;

// From File->Print, File->Print Preview or

// by executing a window.print() command

//

window.οnbefοreprint=beforePrint
window.οnafterprint=afterPrint

function beforePrint() {
appendlinks(content);
}

function afterPrint() {
removelinks(appendedlinks);
}


//

// Generic print function, called from the web page

//

function printContent() {
if (window.print) {
window.print();
} else {
alert("your browser doesn't support this function")
}
}


//

// When appending links to the document, do not

// append links pointing to the following domains / sites

//


var excludedomains=["soderlind.no", "soderlind.org","localhost"]
var excludedomains=excludedomains.join("|")
rexcludedomains=new RegExp(excludedomains, "i")

//

// appendlinks(id)

// id = id of the part of the web page you want to extract links from

// ex: document.body

//


function appendlinks(id){

var strD = "<p/>";
var num = 0;
if (document.getElementById){
var links=id.getElementsByTagName("A")
var total=links.length
strD += "<dl id=/"appendedlinks/" border=0>"
strD += "<dt><h2>Links extracted from the document:</h2></dt>"
for (i=0;i<total;i++){
if (links[i].hostname.search(rexcludedomains)==-1
&& links[i].href.indexOf("http:")!=-1) {
strD += '<dt>'+links[i].innerText+'</dt>'
strD += '<dd>'+links[i]+'</dd>'
num++;
}
}
strD += "</dl>"

if (id.insertAdjacentHTML && num>0)
id.insertAdjacentHTML("beforeEnd",strD);
}
}

//

// removelinks(id)

// After the print job is done, remove the appended links from the document

// id = appendedlinks

//

function removelinks(id) {
if (document.getElementById){
id.removeNode(true);
}
}

Have fun coding (and printing).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Per S



Occupation: Web Developer
Location: Norway Norway

From: http://www.codeproject.com/KB/HTML/printingwithstyle.aspx
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Premium Materials Gallery</title> <style> /* 容器样式 */ .luxemg-container { max-width: 80%; margin: 0 auto; padding: 40px 20px; position: relative; } /* 标题区域 */ .luxemg-header { text-align: center; margin-bottom: 50px; padding-bottom: 20px; border-bottom: 1px solid #e0e0e0; } .luxemg-title { font-weight: 300; letter-spacing: 2px; color: #333; margin: 0 0 10px 0; font-size: 28px; } .luxemg-subtitle { color: #7a7a7a; max-width: 600px; margin: 0 auto; line-height: 1.6; } /* 网格布局 */ .luxemg-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 30px; } /* 卡片样式 */ .luxemg-card { background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 5px 15px rgba(0,0,0,0.05); transition: transform 0.3s ease, box-shadow 0.3s ease; position: relative; display: flex; flex-direction: column; height: 100%; } .luxemg-card:hover { transform: translateY(-8px); box-shadow: 0 12px 25px rgba(0,0,0,0.08); } .luxemg-card-image { height: 240px; overflow: hidden; background: #f8f8f8; } .luxemg-card-img { width: 100%; height: 100%; object-fit: cover; transition: transform 0.5s ease; } .luxemg-card:hover .luxemg-card-img { transform: scale(1.05); } .luxemg-card-content { padding: 25px; flex-grow: 1; display: flex; flex-direction: column; } .luxemg-card-title { font-weight: 400; margin: 0 0 15px 0; font-size: 22px; letter-spacing: 1px; color: #222; } .luxemg-card-desc { color: #666; line-height: 1.7; margin: 0 0 20px 0; font-size: 16px; flex-grow: 1; } /* 详情按钮样式 */ .luxemg-detail-btn { display: inline-block; padding: 10px 20px; background: #000; color: white; border: 2px solid #000; border-radius: 4px; cursor: pointer; font-weight: 500; letter-spacing: 1px; text-transform: uppercase; font-size: 14px; transition: all 0.3s ease; align-self: flex-start; } .luxemg-detail-btn:hover { background: white !important; color: black !important; } /* 模态框样式 */ #luxemg-modal-container { position: fixed; top: 0; left: 10%; width: 100%; height: 100%; background: rgba(0,0,0,0.8); display: none; z-index: 10000; opacity: 0; transition: opacity 0.3s ease; } .luxemg-modal-wrapper { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; padding: 20px; box-sizing: border-box; } .luxemg-modal-content { background: white; width: 100%; max-width: 900px; max-height: 90vh; border-radius: 8px; overflow: hidden; display: flex; flex-direction: column; box-shadow: 0 20px 40px rgba(0,0,0,0.3); transform: scale(0.95); transition: transform 0.4s cubic-bezier(0.18, 0.89, 0.32, 1.28), opacity 0.3s ease; opacity: 0; } .luxemg-modal-header { display: flex; justify-content: space-between; align-items: center; padding: 20px; border-bottom: 1px solid #eee; } .luxemg-modal-title { margin: 0; font-size: 24px; font-weight: 400; color: #333; } .luxemg-close-btn { background: none; border: none; font-size: 24px; cursor: pointer; color: #888; transition: color 0.3s; } .luxemg-close-btn:hover { color: #333; } .luxemg-modal-body { display: flex; overflow: auto; flex-grow: 1; padding: 0; } .luxemg-modal-image-container { width: 50%; min-width: 300px; background: #f8f8f8; display: flex; align-items: center; justify-content: center; padding: 30px; } .luxemg-modal-img { max-width: 100%; max-height: 400px; object-fit: contain; } .luxemg-modal-description { width: 50%; padding: 30px; overflow-y: auto; } .luxemg-modal-desc { line-height: 1.8; color: #555; } .luxemg-specs-table { width: 100%; border-collapse: collapse; margin-top: 25px; font-size: 15px; } .luxemg-specs-table th { padding: 10px; text-align: left; border-bottom: 1px solid #eee; background: #f5f5f5; } .luxemg-specs-table td { padding: 10px; border-bottom: 1px solid #eee; } /* 响应式设计 */ @media (max-width: 1024px) { .luxemg-grid { grid-template-columns: repeat(2, 1fr); } } @media (max-width: 768px) { .luxemg-container { padding: 30px 15px; } .luxemg-grid { grid-template-columns: 1fr; gap: 25px; } .luxemg-card { max-width: 500px; margin: 0 auto; } .luxemg-modal-body { flex-direction: column; } .luxemg-modal-image-container, .luxemg-modal-description { width: 100% !important; } .luxemg-modal-image-container { height: 300px; min-height: auto; } } @media (max-width: 480px) { .luxemg-title { font-size: 24px; } .luxemg-card-title { font-size: 20px; } .luxemg-card-desc { font-size: 15px; } } @media (max-height: 700px) { .luxemg-modal-content { max-height: 85vh; } } </style> </head> <body> <div class="luxemg-container"> <!-- 材料展示网格 --> <div class="luxemg-grid"> <!-- 材料项 1 --> <div class="luxemg-card"> <div class="luxemg-card-image"> <img src="https://www.fetchingpack.com/wp-content/uploads/2025/06/ChatGPT-Image-2025年6月18日-16_45_42_compressed.png" alt="double-sided coated paper" class="luxemg-card-img"> </div> <div class="luxemg-card-content"> <h3 class="luxemg-card-title">double-sided coated paper</h3> <button class="luxemg-detail-btn" data-luxemg-modal="modal1">VIEW MORE</button> </div> </div> <!-- 材料项 2 --> <div class="luxemg-card"> <div class="luxemg-card-image"> <img src="https://via.placeholder.com/600x400/e8极8e8/999999?text=Oak+Hardwood" alt="Oak Hardwood" class="luxemg-card-img"> </div> <div class="luxemg-card-content"> <h3 class="luxemg-card-title">Oak Hardwood</h3> <p class="luxemg-card-desc">European white oak with natural grain patterns...</p> <button class="luxemg-detail-btn" data-luxemg-modal="modal2">VIEW MORE</button> </div> </div> <!-- 材料项 3 --> <div class="luxemg-card"> <div class="luxemg-card-image"> <img src="https://via.placeholder.com/600x400/e8e8e8/999999?text=Brushed+Brass" alt="Brushed Brass" class="luxemg-card-img"> </div> <div class="luxemg-card-content"> <h3 class="luxemg-card-title">Brushed Brass</h3> <p class="luxemg-card-desc">Hand-finished brass with subtle texture...</p> <button class="luxemg-detail-btn" data-luxemg-modal="modal3">VIEW MORE</button> </div> </div> <!-- 材料项 4 --> <div class="luxemg-card"> <div class="luxemg-card-image"> <img src="https://via.placeholder.com/600x400/e8e8e8/999999?text=Ceramic+Tiles" alt="Ceramic Tiles" class="luxemg-card-img"> </div> <div class="luxemg-card-content"> <h3 class="luxemg-card-title">Ceramic Tiles</h3> <p class="luxemg-card-desc">High-gloss ceramic tiles with exceptional durability...</p> <button class="luxemg-detail-btn" data-luxemg-modal="modal4">VIEW MORE</button> </div> </div> </div> </div> <!-- 模态框容器 --> <div id="luxemg-modal-container" class="luxemg-modal-container"> <div class="luxemg-modal-wrapper"> <div class="luxemg-modal-content"> <div class="luxemg-modal-header"> <h3 id="luxemg-modal-title" class="luxemg-modal-title">Material Details</h3> <button id="luxemg-close-modal" class="luxemg-close-btn">×</button> </div> <div class="luxemg-modal-body"> <div class="luxemg-modal-image-container"> <img id="luxemg-modal-image" class="luxemg-modal-img" src="" alt="Material"> </div> <div class="luxemg-modal-description"> <div id="luxemg-modal-description" class="luxemg-modal-desc"></div> <table class="luxemg-specs-table"> <thead> <tr> <th>Property</th> <th>Value</th> </tr> </thead> <tbody id="luxemg-modal-specs" class="luxemg-specs-body"></tbody> </table> </div> </div> </div> </div> </div> <script> // 使用IIFE创建私有作用域避免全局污染 (function() { // 材料详情数据 - 使用唯一前缀 const luxemgMaterialDetails = { modal1: { title: "Italian Marble", image: "https://via.placeholder.com/800x600/e8e8e8/999999?text=Italian+Marble+Detail", description: "<p>Premium Carrara marble quarried directly from the Apuan Alps in Tuscany, Italy. This exquisite natural stone features distinctive soft gray veining on a white or blue-gray background, creating timeless elegance.</p><p>Each slab is carefully selected for its unique pattern and quality, ensuring minimal imperfections. Ideal for high-end countertops, flooring, and feature walls. The marble undergoes a specialized polishing process to enhance its natural luster and durability.</p>", specs: [ { property: "Origin", value: "Carrara, Italy" }, { property: "Hardness", value: "3-4 on Mohs scale" }, { property: "Thickness", value: "2cm, 3cm" }, { property: "Finish", value: "Polished, Honed" }, { property: "Maintenance", value: "Sealing recommended" } ] }, modal2: { title: "Oak Hardwood", image: "https://via.placeholder.com/800x600/e8e8e8/999999?text=Oak+Hardwood+Detail", description: "<p>European white oak (Quercus robur) sourced from sustainably managed forests. This premium hardwood features a straight grain with occasional swirls and burls, offering a warm, natural appearance.</p><p>The wood undergoes a meticulous kiln-drying process to achieve optimal moisture content (8-10%), ensuring dimensional stability. Available in various grades from rustic to select, suitable for flooring, furniture, and architectural elements. The natural tannin content provides inherent resistance to insects and decay.</p>", specs: [ { property: "Species", value: "Quercus robur" }, { property: "Janka Hardness", value: "1360 lbf" }, { property: "Density", value: "720 kg/m³" }, { property: "Moisture Content", value: "8-10%" }, { property: "Sustainability", value: "FSC Certified" } ] }, modal3: { title: "Brushed Brass", image: "https://via.placeholder.com/800x600/e8e8e8/999999?text=Brushed+Brass+Detail", description: "<p>Hand-finished brass with a distinctive brushed texture that diffuses light and minimizes fingerprints. This premium alloy contains 85% copper and 15% zinc, offering a warm golden hue that develops a rich patina over time.</p><p>The brushing process creates subtle linear patterns that enhance depth and character. A protective lacquer coating is applied to preserve the finish while allowing for natural aging. Ideal for hardware, fixtures, and decorative accents in both contemporary and traditional settings.</p>", specs: [ { property: "Composition", value: "85% Copper, 15% Zinc" }, { property: "Finish", value: "Satin Brushed" }, { property: "Thickness", value: "1.2mm - 3mm" }, { property: "Protection", value: "Clear Lacquer Coated" }, { property: "Patina Development", value: "Slow, even" } ] }, modal4: { title: "Ceramic Tiles", image: "https://via.placeholder.com/800x600/e8e8e8/999999?text=Ceramic+Tiles+Detail", description: "<p>High-gloss ceramic tiles manufactured using advanced digital printing technology that replicates natural stone with remarkable fidelity. The durable glaze is formulated for exceptional scratch and stain resistance.</p><p>These tiles feature a through-body color composition, meaning any chips or scratches are less noticeable. The rectified edges allow for minimal grout lines (as small as 1.5mm), creating a seamless appearance. Suitable for both walls and floors in high-traffic areas.</p>", specs: [ { property: "Material", value: "Porcelain Ceramic" }, { property: "PEI Rating", value: "IV (Heavy Traffic)" }, { property: "Water Absorption", value: "<0.5%" }, { property: "Slip Resistance", value: "R10 (Dry)" }, { property: "Sizes", value: "60x60cm, 30x60cm" } ] } }; // DOM元素引用 const luxemgModalContainer = document.getElementById('luxemg-modal-container'); const luxemgModalTitle = document.getElementById('luxemg-modal-title'); const luxemgModalImage = document.getElementById('luxemg-modal-image'); const luxemgModalDescription = document.getElementById('luxemg-modal-description'); const luxemgModalSpecs = document.getElementById('luxemg-modal-specs'); const luxemgCloseModal = document.getElementById('luxemg-close-modal'); // 打开模态框函数 function openLuxemgModal(modalId) { const material = luxemgMaterialDetails[modalId]; const modalContent = luxemgModalContainer.querySelector('.luxemg-modal-content'); if (!material) { console.error("Material details not found for:", modalId); return; } // 填充模态框内容 luxemgModalTitle.textContent = material.title; luxemgModalImage.src = material.image; luxemgModalImage.alt = material.title; luxemgModalDescription.innerHTML = material.description; // 填充技术规格 luxemgModalSpecs.innerHTML = ''; material.specs.forEach(spec => { const row = document.createElement('tr'); row.innerHTML = ` <td>${spec.property}</td> <td>${spec.value}</td> `; luxemgModalSpecs.appendChild(row); }); // 显示模态框 luxemgModalContainer.style.display = 'block'; // 强制重绘确保动画执行 void luxemgModalContainer.offsetWidth; // 应用显示动画 setTimeout(() => { luxemgModalContainer.style.opacity = '1'; modalContent.style.transform = 'scale(1)'; modalContent.style.opacity = '1'; }, 10); // 禁止背景滚动 document.body.style.overflow = 'hidden'; } // 关闭模态框函数 function closeLuxemgModal() { const modalContent = luxemgModalContainer.querySelector('.luxemg-modal-content'); luxemgModalContainer.style.opacity = '0'; modalContent.style.transform = 'scale(0.95)'; modalContent.style.opacity = '0'; setTimeout(() => { luxemgModalContainer.style.display = 'none'; document.body.style.overflow = ''; }, 300); } // 事件绑定函数 function initLuxemgGallery() { // 绑定关闭按钮 luxemgCloseModal.addEventListener('click', closeLuxemgModal); // 点击背景关闭 luxemgModalContainer.addEventListener('click', function(e) { if (e.target === this) closeLuxemgModal(); }); // ESC键关闭 document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeLuxemgModal(); }); // 绑定详情按钮 const detailButtons = document.querySelectorAll('.luxemg-detail-btn'); detailButtons.forEach(button => { button.addEventListener('click', function() { const modalId = this.getAttribute('data-luxemg-modal'); console.log("Opening modal:", modalId); openLuxemgModal(modalId); }); }); console.log("Gallery initialized. Found", detailButtons.length, "detail buttons."); } // DOM加载完成后初始化 document.addEventListener('DOMContentLoaded', initLuxemgGallery); })(); </script> </body> </html> 去掉这段代码中的卡片上的文字描述,保留标题和按钮
06-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值