本地图片上传预览

加了一些美化,将div下的input标签宽高100%,就可以达到鼠标hover上div就能触动input标签,推荐地址:地址

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .div-img {
            background-color: #ccc;
            width: 300px;
            height: 300px;
            background-image: url('');
        }

        .div-file {
            width: 100px;
            height: 30px;
            border: 2px solid yellow;
            border-radius: 5px;
            text-align: center;
            line-height: 30px;
            position: relative;
        }

        input {
            width: 100%;
            height: 100%;
            opacity: 0;
            z-index: 999;
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="div-img">
    </div>
    <div class="div-file">
        点击
        <input class="inp-img" type="file">
    </div>
    <script>
        var div_img = document.getElementsByClassName('div-img')[0];
        var inp_img = document.getElementsByClassName('inp-img')[0];
        //检测浏览器是否支持FileReader
        if (typeof (FileReader) === 'undefined') {
            result.innerHTML = "抱歉,你的浏览器不支持 FileReader,请使用现代浏览器操作!";
            inp_img.setAttribute('disabled', 'disabled');
        } else {
            //开启监听
            inp_img.addEventListener('change', readFile, false);
        }
        function readFile() {
            var file = this.files[0];
            //限定上传文件的类型,判断是否是图片类型
            if (!/image\/\w+/.test(file.type)) {
                alert("只能选择图片");
                return false;
            }
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                base64Code = this.result;
                console.dir(base64Code);
                div_img.style.backgroundImage = `url(${base64Code})`;
            }
        }
    </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/wuqiuxue/p/8982120.html