Demand: H5 call with the phone camera and photo albums in order to achieve functional replacement avatar
This function is a very common feature, so make a record.
1. Add a file input box in the picture img
<input type="file" id="file" accept="image/*" capture='camera' multiple>
And hide it
1 <center> 2 <img src="images/[email protected]" class="avatar"> 3 <input type="file" id="file" accept="image/*" capture='camera' multiple> 4 </center>
1 #file { 2 display: none; 3 }
2. Click the picture file input box click on the trigger event
$(".avatar").click(function(){ $("#file").trigger("click") })
3. By js files get uploaded content, converted to base64 encoded and displayed on the page picture
1 //ios去掉capture属性 2 var file = document.querySelector('input'); 3 if (getIos()) { 4 file.removeAttribute("capture"); 5 } 6 function getIos() { 7 var ua = navigator.userAgent.toLowerCase(); 8 if (ua.match(/iPhone\sOS/i) == "iphone os") { 9 return true; 10 } else { 11 return false; 12 } 13 }
1 // turn into Base64 2 $ ( 'INPUT [type = File]') ON ( 'Change',. Function () { . 3 var Reader = new new the FileReader (); . 4 reader.onload = function (E) { . 5 Console .log (reader.result); // or e.target.result are the same, are base64 code . 6 $ ( "Avatar.") attr ( "the src." , reader.result); . 7 } . 8 Reader. readAsDataURL ( the this .files [0 ]) . 9 // filses is input [type = file] list file, files [0] is the first file, this is the first selected image files into a base64 code 10 } )
4. achieve results page display
Replacement effect before the picture:
Replacement effect after the picture: