It took me two days to figure out how to preview the picture.
mission requirements are as follows:
There is a picture on the 1:jsp page (pic_1)
2: Click on the picture to eject the interface similar to the resource manager
3: Preview After selecting a picture at pic_1
I am on the IE8 test the following code, you can achieve the above functions, not in other browsers test, if you friends know a variety of browser support methods, please enlighten, learn together, thank you.
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>insert title here</title>
<script type= "Text/javascript" >
function Tempclick () {
/**
* Firefox browser to achieve click on the image file upload interface
* var a=document.createevent ("Mouseevents");
* A.initevent ("click", True, true);
* document.getElementById ("upload_main_img"). Dispatchevent (a);
*/
IE browser to achieve click on the image file upload interface
document.getElementById (' main_img '). Click (); Call the Main_img onclick event
}
/**
* Preview Picture
* @param obj
* @returns {Boolean}
*/
function previewimg (obj) {
var Newpreview = document.getElementById ("img_2");
var imgpath = GetPath (obj);
alert (Imgpath);
if (!obj.value.match (/.jpg|). Gif|. Png|. bmp/i)) {
Alert ("Picture format is wrong!") ");
return false;
}
NewPreview.style.filter = "Progid:DXImageTransform.Microsoft.AlphaImageLoader (Sizingmethod=scale)";
NewPreview.filters.item ("DXImageTransform.Microsoft.AlphaImageLoader"). src = Imgpath;
}
/**
* Get Picture absolute path
* @param obj
* @returns
*/
function GetPath (obj) {
if (obj) {
if (Navigator.userAgent.indexOf ("MSIE") >0) {
Obj.select ();
IE get the local path to the picture
Return Document.selection.createRange (). text;
else if (Isfirefox=navigator.useragent.indexof ("Firefox") >0) {
if (obj.files) {//Firefox gets the data of the picture
Return Files.item (0). Getasdataurl ();
}
return obj.value;
}
return obj.value;
}
}
</script>
<body>
<form>
<div><input type= "File" style= "Position:absolute; Filter:alpha (opacity = 0); opacity:0; width:30px "size=" 1 "id=" main_img "name=" main_img "onchange=" previewimg (This) "></div>
<div id= "img_2" style= "width:133px;height:95px; Cursor:pointer; Background-image:url (' chrysanthemum.jpg '); "onclick=" Tempclick () ></div>
</form>
</body>
A simple explanation of the code:
Input type= "file" This element I have tried to let the style hide (style= "Display:none"), so that you can not or get an absolute path, but fakepath, in order to not let it show to let him 100% transparent, there is a div below, ID is img_2, this div is the page initial picture, click this picture to call input type= "file" in the method, realize this function.
Limited capacity, but also please advise, there is a better way please provide me, learn together, thanks.