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

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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.

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools