仅在打印上使用DOM操作 [英] DOM manipulation on print only

查看:160
本文介绍了仅在打印上使用DOM操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做

  $('#foo')。insertAfter('#bar'); 

仅在用户打印页面时。我不想在屏幕上执行任何脚本。



我知道如果我想操作样式,这将是简单的,因为我将刚刚使用 @media print {} 在CSS中。然而,我试图实现的目标(DOM操纵)不能用CSS实现,因此我需要使用JS。



如何运行JavaScript(或jQuery)<

解决方案

如果您不在乎跨浏览器功能可以使用 window.onbeforeprint 事件,但它只支持在IE和firefox 6 +

  window.onbeforeprint = function(){
$('#富 ')insertAfter(' #巴');
};

另一种方法是覆盖CTRL + P击键

  window.onkeydown = function(e){
var char = String.fromCharCode(e.keyCode);
if(char ==P& e.ctrlKey){
$('#foo')。insertAfter('#bar');
}
};


I want to do

$('#foo').insertAfter('#bar');

but only when the user prints the page. I don't want to do any scripting while on screen.

I realize this would have been simple if I wanted to manipulate styles, because then I would have just used @media print {} in CSS. However the goal I am trying to achieve (DOM manipulation) cannot be achieved with CSS, hence I need to use JS.

How can I run JavaScript (or jQuery) only when the user prints or does print-preview?

解决方案

If you do not care about cross browser functionality you can use the window.onbeforeprint event, but it is only supported in IE and firefox 6+

window.onbeforeprint = function(){
     $('#foo').insertAfter('#bar');
};

Another way is to override the CTRL+P keystrokes

window.onkeydown = function(e){
  var char = String.fromCharCode(e.keyCode);  
  if(char == "P" && e.ctrlKey){
      $('#foo').insertAfter('#bar');
  }
};

Fiddle

But this will not work if the user uses the menu system to do a print or right clicks to print.

这篇关于仅在打印上使用DOM操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆