简体   繁体   中英

Click image and open file upload

I'm trying to get my image onclick to open a file uploader but nothing is working.

html:

    <a href="#">
  <figure class="profile-picture" id="profile-picture">
  </figure>
  </a>

css:

figure.profile-picture {
  background-position: center center;
  background-image: url(/img/QNdefualt.jpg);
  background-size: cover;
  border: 5px #efefef solid;
  border-radius: 50%;
  bottom: -50px;
  box-shadow: inset 1px 1px 3px rgba(0,0,0,0.2), 1px 1px 4px gba(0,0,0,0.3);
  height: 148px;
  left: 150px;
  position: absolute;
  width: 148px;
  z-index: 3;
}   
.profile-picture:hover {
   background-image: url(/img/defualt-hover.png);
   background-size: cover;
}

I've tried onclicks but I keep getting errors. Please help.

You will need to add an input element with type=file . It does not has to be visible. Listen for click events on your image, and trigger a .click() on the hidden input element.

Here is an example.

 var imgBtn = document.querySelector('img'); var fileInp = document.querySelector('[type="file"]'); imgBtn.addEventListener('click', function() { fileInp.click(); }) 
 input[type="file"] { display: none; } img { cursor: pointer; } 
 <input type="file" /> <img src="http://placehold.it/200x200/2980b9/FFF?text=Click Me" alt=""> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM