有一个通用的解决方案,以及一些旧版浏览器的骇客。您可以覆盖的print()
方法在所有浏览器:
(function (oldPrint) {
window.print = function() {
document.getElementById("hideThis").style.display = 'none';
oldPrint();
}
})(window.print);
这里的问题是,它不会触发用户按Ctrl + P或访问文件菜单进行打印。 Internet Explorer有由onbeforeprint
事件的方式加以解决:
if ("onbeforeprint" in window) {
var hideEl = document.getElementById("hideThis");
window.onbeforeprint = function() {
hideEl.style.display = 'none';
}
window.onafterprint = function() {
hideEl.style.display = '';
}
}
至于其他浏览器,你可以到打印MediaQueryList添加事件侦听器为detailed by TJ VanToll in another answer:
if (window.matchMedia) {
var mqList = window.matchMedia("print"),
hideEl = document.getElementById("hideThis");
mqList.addListener(function (mql) {
hideEl.style.display = mql.matches ? 'none' : '';
});
}
,并把它们放在一起:
(function() {
var hideEl = document.getElementById("hideThis");
// HTML5 spec, IE 5.5+, Firefox 6.0+
if ("onbeforeprint" in window) {
window.onbeforeprint = function() {
hideEl.style.display = 'none';
}
window.onafterprint = function() {
hideEl.style.display = '';
}
}
// Chrome 9+, Opera 12.1+, Safari 5.1+
else if (window.matchMedia) {
var mqList = window.matchMedia("print");
mqList.addListener(function (mql) {
hideEl.style.display = mql.matches ? 'none' : '';
});
}
// Your fallback method, only working for JS initiated printing
else {
(function (oldPrint) {
window.print = function() {
hideEl.style.display = 'none';
oldPrint();
}
})(window.print);
}
})();
为什么不能在打印特定的样式表中显示:none? – 2010-09-01 15:20:52
我已经试过了,节点不标准,显示:none!important; css什么也没变。 – Pricey 2010-09-01 15:24:42
@Pricey:你可能没有这个问题了,但我想我会让你知道现代浏览器有更好的解决方案。详情请参阅下面的答案。 – 2013-01-15 21:43:00