js call cell phone camera or album and show pictures

 

Renderings

Mobile browser, open the page micro-channel, support call camera, camera and open the album.

Look at the final results: 

 CPC "Click Upload", you can select an album or camera, can be more complete after the election to show a picture, do not upload server here.

Click "Re-upload", emptied all the pictures.

 

 

PC browser opens, similar, but only select image files:

 

 

 Code

 

The transparency input type = file tag is set to 0, the absolute layout used to cover it with another tag:

<div id="imgPreview">
    <div id="prompt3">
        <div id="imgSpan">
            点击上传
        </div>
        <input type="file" id="file" class="filepath" onchange="changepic()" accept="image/*">
        <button id="imgSpan" type="button" onclick="clearpic()">重新上传</button>
    </div>
    @*此处用js自动插入图片标签<img src="" id="img3" />*@
</div>

 

获取到图片以后在前端展示图片:

function changepic() {
    var reads = new FileReader();
    f = document.getElementById('file').files[0];
    reads.readAsDataURL(f);
    reads.onload = function (e) {
        var y = document.createElement('img');
        y.id = "img3";
        y.src = this.result;
        $("#imgPreview").append(y);
    };
};

 

通过遍历删除第一个以外的所有标签(第一个标签是上传和清空的按钮):

function clearpic() {
    var x = document.getElementById('imgPreview');
    var count = x.childElementCount;
    alert(count);
    for (var i = 1; i < count;i++) {   
        x.removeChild(x.children[1]);
    }
};

 

css 样式:

#imgPreview {
    width: 100%;
    height: 120px;
    margin: 10px auto 0px auto;
    border: 0.5px solid #ced4da;
    text-align: left;
    vertical-align: central;
}

#prompt3 {
    height: 30px;
    width: 200px;
    position: relative;
}

#imgSpan {              -》》 两个按钮的样式
    position: relative;
    height: 30px;
    background: #fff; /*#ccc;*/
    border: 1px solid #333;
    left: 0;
    top: 1px;
    padding: 5px 10px;
    overflow: hidden;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
    border-radius: 20px;
    color: #333;
    font-size: 13px;
    display: inline;
}

.filepath {
    position: absolute;    -》》绝对布局
    left: 0;
    top: 0;
    height: 30px;
    width: 80px;
    opacity: 0;          -》》 透明度设置为0,即隐藏
}

#img3 {
    position: relative;
    height: 90px;
    width: 90px;
    padding: 2px;
    display: inline;       -》》inline是为了让所有图片不换行
}

 

Guess you like

Origin www.cnblogs.com/hongwei918/p/11370000.html