您的位置:首頁 > 網絡資訊 > 網頁設計

新聞詳細

讓javascript文件跨瀏覽器實現圖片數據攜帶
2011-04-21 來源:思派網絡 [ ]

現代瀏覽器可以基於RFC 2397標準使用base64把圖片進行編碼,然後輸出類似data:image/png;base64,iVBORw0KGgoAA…。的文本即可。 RFC 2397標準製定與1998年,至今IE6、7仍不支持,如果想要實現文本攜帶圖像數據,俄羅斯某大俠寫了這麽一篇文章:http://webo.in/articles/habrahabr/46-cross-browser-data-url/

文章指出可以利用mhtml協議方式把含有圖片數據mht格式的文件鏈接進來,這個mht格式數據可以寫到css、html或者js的注釋中,引用的時候直接鏈接即可。

關於mht格式在百度百科中的定義:

mht是一種WEB電子郵件檔案,能用瀏覽器打開的前提是你的機子上必須裝有Outlook Express !在手机赌博點菜單-》文件-》另存為…後在選擇保存類型時可以看到有這一項,其最大優點是所保存的網頁隻有一個文件,便於管理。而以 (*.htm;*.html)保存的網頁,你會看到其實有一個網頁和相應的一個文件夾,IE把頁麵元素分開存放了。說白了,該文件就是你從瀏覽器中看到的網頁的全部。

MHT叫“web單一文件”。顧名思義,就是網頁中包含得圖片,CSS文件以及HTML文件全部放到一個MHT文件裏麵。mht就是mono html,就是獨立的HTML文件,他是IE在save as時將頁麵中所有可以收集的元素全部存放在一個頁麵裏,當然尺寸就大了啦,不過倒省卻了相對路徑絕對路徑的煩心事。

下麵我把“李小龍”的一張圖片經過base64編碼後嵌入javascript,例如:

 

/*Content-Type: multipart/related; boundary="_ANY_STRING_WILL_DO_AS_A_SEPARATOR"--_ANY_STRING_WILL_DO_AS_A_SEPARATORContent-locations:%E5%94%90%E6%96%8CContent-Transfer-Encoding:base64iVBORw0KGgoAAAANSUhEUgAAAPAAAACJCAMAAAAlpkWpAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACRQTFRF5+vt1s+9yql2joyHb2tjIyAj0rOBcVQ1oIFXSzsuy8GurayofdFEagAADapJREFUeNrsneli46oOgFlkQPD+73u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JZ4577zF4H9vZ5a3Lw3p2yI9z1DSHevd8+v8EZAOO4Sp+1bc87Ig1Sj+ONNhc9KGHVjAg8/9mHVYtLoddpgWnjgtj54Nh5xVXXvYxAmE4Zy1ob422noA1p9mOfVo6yU6Zy2P/xuFvpIaDr0WlkuBI3+vM20J1Z5lZfb+Mfug3cdrb0iML4MfEfEt+sywPl1XhJx/nvAr1ow/qDTVwV+2YKl0n1Cp68C/LIFy22BAPmPAfs3PJYAl78F/JbHIuWA+MeAYXlr8S7KnwLOy9vA8BTwP/cp8f/W+p8AAwBcNiMCbK0DdAAAAABJRU5ErkJggg==*/(function () {	var doc = document,		isMhtml = !-[1,] && !('prototype' in Image),		url = doc.getElementsByTagName('script'),		ajax = function (url, fn){			var XHR = new XMLHttpRequest();			XHR.onreadystatechange = function(){				XHR.readyState === 4 && XHR.status === 200 && fn(XHR.responseText);			};			XHR.open('GET', url, 1);			XHR.send(null);		},		setStyle = function (content) {			var style = doc.createElement('style');			doc.getElementsByTagName('head')[0].appendChild(style);			style.styleSheet && (style.styleSheet.cssText += content) || style.appendChild(doc.createTextNode(content));		};	url = url[url.length - 1].getAttribute('src', 4);	isMhtml ? setStyle('.dataUrlScheme{*background-image:url("mhtml:' + url + '!%E5%94%90%E6%96%8C")}') :	ajax (url, function (data) {		data = 'http://www.chinaz.com/Design/Pages/.dataUrlScheme{background-image:url("data:image/png;base64,' + data.split('base64\r\n\r\n')[1].split('\r\n')[0] + '")}';		setStyle(data);	});})();

我原來嚐試使用js把MHT動態寫入HTML文件中再引用頁麵地址,可是未能成功,所以隻能靜態嵌入到js文件中。