js implements pure front-end image preview_javascript skills
画像のアップロードは一般的な機能であり、画像のプレビューはアップロード機能の重要なサブ機能です。以前は、input[type=file] 要素の onchange イベントをサブスクライブし、パスが変更されたら画像をサーバーにアップロードし、画像のパスを取得して img 要素に割り当てていました。非同期ファイル送信のソリューションに関係なく、サーバー側で一時的なプレビュー画像をクリーンアップすることは、すでに多くの作業負荷を増加させています。
純粋なフロントエンド画像プレビューに関する関連情報を MDN から偶然発見し、整理した後、将来の参考のために記録しました。
1. 準備1──FileReader
FileReader は HTML5 の新機能で、Blob およびファイル タイプのデータを読み取るために使用されます。具体的な使い方は以下の通りです:
(1). 施工方法
var fr = new FileReader();
(2) 属性
readyState: type is unsigned short、FileReader インスタンスの現在の状態 (EMPTY——0、データはロードされていません。LOADING——1、データがロード中です。DONE——2、すべての読み取りリクエストが完了しました)完了)、読み取り専用。
結果: 読み取られたファイルの内容、読み取り専用。
error: タイプは DOMError で、ファイルの読み取り時に発生したエラーを示します (読み取り専用)。
(3) メソッド
abort(): 読み取り操作を中止し、readyState を DONE に設定します。読み取り操作が実行されない場合、このメソッドを呼び出すと DOM_FILE_ABORT_ERR 例外がスローされます。
readAsArrayBuffer(Blob blob): データを読み取り、結果の属性は ArrayBuffer タイプに設定されます
readAsText(Blob blob [, encoding='utf-8']): データを読み取り、結果属性は String 型に設定されます
readAsBinaryString(Blob blob): データを読み取り、結果属性は生のバイナリ データに設定されます
readAsDataURL(Blob blob): データを読み取り、結果属性がデータ URI スキーム フォームに設定されます (詳細については、「JS Magic Hall: データ URI スキームの概要」を参照してください)
(4).イベント
onload: データの正常な読み取り後にトリガーされます
onerror: データの読み取り時に例外がスローされたときにトリガーされます
onloadstart: データを読み取る前にトリガーされます
onloadend: データの読み取り後にトリガーされ、onload または onerror 後にトリガーされます
onbort: 読み取りを中止した後にトリガーされます
進行中: 読み取りプロセス中に定期的にトリガーされます
(5) ブラウザは
をサポートします。FF3.6+、Chrome7+、IE10+
2.準備2──DXImageTransform.Microsoft.AlphaImageLoaderフィルター
(1). 機能: 主な機能は画像を透明にすることです (IE5.5~6 は透明 PNG をサポートしていません)
(2) スタイルでの使い方
#preview{ filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="dummy.png"); }
(3) JSでの使い方
var preview = document.getElementById('preview'); preview.style.filter = preview.currentStyle.filter + ";progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src='dummy.png')"; preview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src="dummy1.png";
(4) 属性
。enabled: オプションで、フィルターを有効にするかどうかを設定します。値の範囲 true (デフォルト)、false
sizingMethod: オプション。フィルタリングされた画像をコンテナ境界内で表示する方法、値の範囲トリミング (コンテナ サイズに合わせて画像を切り取る)、画像 (デフォルト値、画像に合わせてコンテナ サイズを増減する) サイズを設定します。 )、スケール (コンテナーのサイズに合わせて画像をスケールします)
src: 必須。絶対 URL または相対 URL を使用して背景画像を指します。 URLがユーザーのコンピュータのローカルアドレスの場合に有効で、img要素のsrcがユーザーのコンピュータのローカルアドレスの場合は、ローカルファイルシステムへのアクセスを許可しない例外がスローされます。
3 つの 、実装
次に、FileReader の readAsDataURL を使用して、画像プレビュー機能を実装するための Data URI Scheme を取得します。IE5.5 ~ 9 では、ダウングレード処理にフィルター DXImageTransform.Microsoft.AlphaImageLoader を使用します。
HTML フラグメント:
<style type="text/css"> #preview{ width: 100px; height: 100px; } </style> <!--[if lte IE 9]> <style type="text/css"> #preview{ filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale); } </style> <![endif]--> <input type="file" onchange="showPreview(this);"/> <div id="preview"> </div>
js スニペット:
var preview = function(el){ var pv = document.getElementById("preview"); // IE5.5~9使用滤镜 if (pv.filters && typeof(pv.filters.item) === 'function'){ pv.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = el.value; } else{ // 其他浏览器和IE10+(不支持滤镜)则使用FileReader var fr = new FileReader(); fr.onload = function(evt){ var pvImg = new Image(); pvImg.style.width = pv.offsetWidth + 'px'; pvImg.style.height = pv.offsetHeight + 'px'; pvImg.src = evt.target.result; pv.removeChild(0); pv.appendChild(pvImg); }; fr.readAsDataURL(el.files[0]); } };
4. 落とし穴
IE11 ではセキュリティ上の考慮事項により、ユーザーが選択したファイルの実際のアドレスは、input[type=file] 要素の value、outerHTML、getAttribute では取得できません。取得できるのは、C: fakepath のファイル名のみです。 。したがって、IE11 を使用していてテキスト モードが 10 未満に設定されている場合、画像プレビューを実行する方法はありません。
解決策 1──次の文を head タグの下に追加します。 。このようにして、デフォルトで Web ページの解析とレンダリングに IE の最新バージョンを使用するように IE に指示できます。
解決策 2── document.selection.createRangeColleciton() を使用して実際のアドレスを取得します。 具体的な操作は次のとおりです。
五、补充:使用window.URL.createObjectURL代替FileReader
通过FileReader的readAsDataURL方法获取的Data URI Scheme会生成一串很长的base64字符串,若图片较大那么字符串则更长,若页面出现reflow时则会导致性能下降。解决方案如下:
1. 预览的img标签使用绝对定位,从而脱离正常文档流,那么就与文档的其他元素无关了,而reflow时则不会影响性能。
2. 采用 window.URL.createObjectURL(Blob blob) 生成数据链接。
var createObjectURL = function(blob){ return window[window.webkitURL ? 'webkitURL' : 'URL']['createObjectURL'](blob); };
注意: window.URL.createObjectURL 生成的数据链接是独占内存的,因此若不时用时需要调用 window.URL.revokeObjectURL(DOMString objUrl) 来释放内存。在刷新页面时,也会自动释放内容。
var resolveObjectURL = function(blob){ window[window.webkitURL ? 'webkitURL' : 'URL']['revokeObjectURL'](blob); };
以上就是本文的全部内容,希望对大家的学习有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
