js打印网页,打印页面,打印局部页面

我来纠错
//打印前都必须引入打印样式,就是媒体用media="all",即可。
<link rel="stylesheet" media="all" href="print.css">

//打印整个页面
if (window.print){
	window.print();
}else{
	alert("您的浏览器不支持自动打印,请使用浏览器的打印功能!");
}

//打印部分网页,打印指定区域页面
(function(window,$){
	function printPartOfDocument() {
	    this.init.apply(this, arguments)
	}
	printPartOfDocument.prototype = {
	    init: function(o, part) {
	        this.o = this.getId(o);
	        this.part = this.getId(part);
	        this.frame = '';
	        this.printCss = '';
	        var _this = this;
	        this.addEvent(this.o, 'click',
	        function() {
	           
	        }); _this.create()
	    },
	    create: function() {
	        var _this = this;
	        if (!this.frame) {
	            var oFrame = document.createElement('iframe');
	            oFrame.setAttribute('id', 'printIframe');
	            oFrame.style.position = 'absolute';
	            oFrame.style.left = '-9999px';
	            oFrame.style.top = '0px';
	            document.body.appendChild(oFrame);
	        }
	        if (!this.printCss) this.printCss = this.getPrintCss();
	        setTimeout(function() {
	            _this.frame = document.getElementById('printIframe'),
	            d = _this.frame.contentWindow.document,
	            h = d.getElementsByTagName('head')[0],
	            b = d.getElementsByTagName('body')[0];
	            for (var i = 0; i < _this.printCss.length; i++) {
	                h.appendChild(_this.printCss[i]);
	                }
	            b.innerHTML = '';
	            b.appendChild(_this.part.cloneNode(true));
	            _this.frame.contentWindow.print();
	        },
	        0);
	    },
	    getPrintCss: function() {
	        var styles = document.getElementsByTagName('head')[0].getElementsByTagName('link'),
	        printCss = [];
	        for (var i = 0; i < styles.length; i++) {
	            var attr = styles[i].getAttribute('media');
	            if (attr == 'all' || attr == 'print') printCss.push(styles[i].cloneNode(true));
	        }
	        return printCss;
	    },
	    getId: function(el) {
	        return typeof el == 'string' ? document.getElementById(el) : el
	    },
	    addEvent: function(o, type, fn) {
	        if (o.addEventListener) {
	            o.addEventListener(type, fn, false)
	        } else if (o.attachEvent) {
	            o.attachEvent('on' + type,
	            function() {
	                fn.call(o, window.event)
	            })
	        }
	    }
	};
	window.printPartOfDocument = printPartOfDocument;
})(window,$);

new printPartOfDocument('print','ceshi'); //调用局部打印,参数1:打印按钮的id;参数2:需要打印的div模块的id;
发送
热门关键词:
命令
知识类型:
标题描述:
详细解答:

提交审核您编辑的知识会经过 前端大牛 人工审核。