KH-WEBLOG TOP > WEBメモ > JavaScript > 印刷範囲を指定した印刷ボタンの実装方法:javascript

印刷範囲を指定した印刷ボタンの実装方法:javascript

最終更新日:

通常の印刷ボタンではサイト全体の印刷になってしまいますが、
部分的に印刷したい場合に印刷範囲を指定した印刷ボタンの実装方法をメモ。

jsに

$.jPrintArea=function(el){
var iframe=document.createElement('IFRAME');
var doc=null;
$(iframe).attr('style','position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc=iframe.contentWindow.document;
var links=window.document.getElementsByTagName('link');
for(var i=0;i<links.length;i++)
if(links[i].rel.toLowerCase()=='stylesheet')
doc.write('<link type="text/css" rel="stylesheet" href="'+links[i].href+'"></link>');
doc.write('<div class="'+$(el).attr("class")+'">'+$(el).html()+'</div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
alert('Printing...');
document.body.removeChild(iframe);
}
$(function(){
  $('#btn_print').click(function(){
    $.jPrintArea("#printarea");
  });
});

と記載します。
※#btn_print、#printareaの箇所は任意に変更

あとは印刷ボタンを設置したい箇所に

<a href="javascript:void(0);" id="btn_print">印刷する</a>

印刷範囲を

<div id="printarea">ここに印刷範囲のコンテンツを記載</div>

でOK

コーディング・WordPress化作業を代行します

JavaScriptのおすすめ参考書

楽天ブックス
¥2,838 (2024/04/23 21:14時点 | 楽天市場調べ)

TAGS

.htaccess ActionScript All in one seo pack Contact Form 7 CSS CSS3 EC-CUBE Flash HTML HTML5 JavaScript jQuery LightBox PHP RSS SEO WordPress アイキャッチ画像 アクセス解析 カスタムフィールド カテゴリー カラーミーショップ カート コメント ショートコード テンプレートタグ ドロップダウンメニュー パーマリンク フォーム フルスクリーン ブログカード プラグイン ページテンプレート ページナビ ページ分割 マウスイベント リダイレクト リンク リンクカード レンタルサーバー ロールオーバー 携帯サイト 条件分岐 正規表現 関連記事