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); };
以上就是本文的全部内容,希望对大家的学习有所帮助。

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
