บทความนี้แชร์รหัสเฉพาะสำหรับการใช้งานฟังก์ชั่นตัวอย่างภาพ JavaScript สำหรับการอ้างอิงของคุณ เนื้อหาเฉพาะมีดังนี้
ก่อนอื่นฉันจะแบ่งปันโค้ดเกี่ยวกับ JS Image Preview กับคุณซึ่งเข้ากันได้กับ Firefox และ Google Chrome กับคุณ
/* เคสแสดงภาพตัวอย่างภาพตัวอย่าง*/$ (function () {$ ("#file0"). bind ("เปลี่ยน", function () {clickupload ();});}); ฟังก์ชั่น clickupload () {var imgobject = document.getElementById ('file0'); var getImagesrc = getfullpath (imgobject); // เส้นทางท้องถิ่น var srcs = window.url.createObjecturl (imgobject.files [0]); var pos = getImagesrc.lastindexof ("."); var lastName = getImagesRc.SubString (pos, getImagesRc.length) // ภาพต่อท้ายของภาพ] ถ้า (srcs! = "") {$ ("#yulan2"). attr ("src", srcs); } else {Alert ("โปรดเลือกรูปภาพ"); }} ฟังก์ชั่น getfullpath (obj) {// รับเส้นทางเต็มของภาพถ้า (obj) {ถ้า (window.navigator.useragent.indexof ("msie")> = 1) {obj.select (); ส่งคืน document.selection.createrange (). ข้อความ; } อื่นถ้า (window.navigator.useragent.indexof ("firefox")> = 1) {ถ้า (obj.files) {return window.url.createObjecturl (obj.files [0]); } return obj.value; } return obj.value; -รหัสตัวอย่างใช้ตัวอย่างที่ทันเวลาของการอัปโหลดรูปภาพโดย JS:
<html> <head> <meta http-equiv = "content-type" content = "text/html; charset = utf-8"/> <title> ภาพอัพโหลดตัวอย่างท้องถิ่น </title> <style type = "text/css">#preview {width: 260px; {ตัวกรอง: progid: dximagetransform.microsoft.alphaimageLoader (sizingMethod = image);} </style> <script type = "text/javascript"> // ie ใช้ตัวกรองสำหรับการอัปโหลดและดูตัวอย่าง ฟังก์ชั่น previewImage (ไฟล์) {var maxWidth = 260; var maxheight = 180; var div = document.getElementById ('ดูตัวอย่าง'); if (file.files && file.files [0]) {div.innerhtml = '<img id = imghead>'; var img = document.getElementById ('imghead'); img.onload = function () {var rect = clacimgzoomparam (maxWidth, maxHeight, img.offsetWidth, img.offSetheight); img.width = rect.width; img.height = rect.height; // img.style.marginleft = rect.left+'px'; img.style.margintop = rect.top+'px'; } var reader = new filereader (); reader.onload = function (evt) {img.src = evt.target.result;} reader.readasdataurl (file.files [0]); } // เข้ากันได้กับ IE {var sfilter = 'ตัวกรอง: progid: dximagetransform.microsoft.alphaimageLoader (sizingMethod = มาตราส่วน, src = "'; file.select (); var src = document.selection.createrange document.getElementById ('imghead'); = ('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height); style = 'ความกว้าง: "+rect.width+" px; ความสูง: "+rect.height+" px; margin-top: "+rect.top+" px; "+sfilter+src+"/"'> </div>" ซ้าย: ความกว้าง: ความกว้าง, ความสูง: ความสูง}; param.width = math.round (ความกว้าง / rateheight); id = "iMghead" width = 100 ความสูง = 100 border = 0 src = '<%= request.getContextPath ()%>/images/default.jpg'> </div> <อินพุตประเภท = "ไฟล์" onChange = "previewImage (นี่)"ข้างต้นเป็นเรื่องเกี่ยวกับบทความนี้ฉันหวังว่ามันจะเป็นประโยชน์สำหรับทุกคนในการเรียนรู้การเขียนโปรแกรม JavaScript