After adding some beautification, set the width and height of the input tag under the div to 100%, so that the input tag can be touched on the div on the mouse hover. Recommended address: address
<!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"> click < input class ="inp-img" type ="file" > </ div > < script > var div_img = document.getElementsByClassName( ' div-img ' )[ 0 ]; var inp_img = document.getElementsByClassName( ' inp -img ' )[ 0 ]; // Check if the browser supports FileReader if ( typeof (FileReader) === ' undefined ' ) { result.innerHTML = " Sorry, your browser does not support FileReader, please use a modern browser! " ; inp_img.setAttribute('disabled', 'disabled'); } else { // Enable listening inp_img.addEventListener( ' change ' , readFile, false ); } function readFile() { var file = this .files[ 0 ]; // Limit the type of uploaded file to determine whether it is an image type if ( ! / image\/\w+ / .test(file.type)) { alert( " Only pictures can be selected " ); 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>