--- title: WindowEventHandlers.onbeforeprint slug: Web/API/WindowEventHandlers/onbeforeprint translation_of: Web/API/WindowEventHandlers/onbeforeprint ---
onbeforeprint属性是用于处理当前窗口的{{event("beforeprint")}}事件的{{event("Event_handlers", "event handler")}}。在打开打印对话窗口之前会触发这些事件。beforeprint和{{event("afterprint")}}事件允许网页在打印开始前更改他们的内容(例如:可能是删除一个横幅),然后在打印完成后恢复这些更改。通常,您应该更喜欢使用@media printCSS规则,但是在某些情况下可能有必要使用这些事件。window.addEventListener("beforeprint", function(event) { ... });
window.onbeforeprint = function(event) { ... };
Safari没有实现这些事件,但是您可以使用创建与beforeprint事件等效的结果。{{domxref("window.matchMedia")}}('print')
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if(mql.matches) {
console.log('webkit equivalent of onbeforeprint');
}
});
| 规范 | 状态 | 注解 |
|---|---|---|
| {{SpecName('HTML WHATWG', '#handler-window-onbeforeprint', 'onbeforeprint')}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.WindowEventHandlers.onbeforeprint")}}