使用class而不是label和input id选择并交换文件

时间:2018-05-22 21:35:26

标签: javascript jquery html

当前代码使用<label for="x"><input id="x">来更改images内的.label

是否有一个更简单的功能,我可以简单地从classlabel的唯一input交换图像,或者我是否需要保持它像它一样?

&#13;
&#13;
function readURL(input) {
  var id = $(input).attr("id");
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('label[for="' + id + '"] .icon').hide();
      $('label[for="' + id + '"] .prev').attr('src', e.target.result).show();
    }
    reader.readAsDataURL(input.files[0]);
  }
}
$("input[id^='file-input']").change(function() {
  readURL(this);
});
$('.prev').each(function() {
  var src = $(this).attr('src');
  if (src && src.trim().length > 0) {
    $(this).siblings('.icon').hide();
  } else {
    $(this).hide();
  }
});
&#13;
.feature-box {
  display: block;
  border: 2px solid;
  position: relative;
  width: 50px;
  height: 50px;
  margin: 10px;
  overflow: hidden;
}

.logo-box {
  background: white;
  display: block;
  position: relative;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  box-shadow: 1px 1px 3px 0 rgba(0, 0, 0, 0.12);
}

.upload-options {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  cursor: pointer;
  overflow: hidden;
}

.upload-options input {
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}

.upload-options label {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  cursor: pointer;
  overflow: hidden;
}

.upload-options label img {
  max-height: 100%;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item1">
  <div class="edit">
    <div class="feature-box">
      <div class="upload-options">
        <label class="label1" for="file-input1">
    <img class="icon" src="https://uploads-ssl.webflow.com/57e5747bd0ac813956df4e96/5aebae14c6d254621d81f826_placeholder.png">
    <img class="prev" src="">
        <input id="file-input1" type="file" name="image" class="image1" accept="image/*"/>
      </label>
      </div>
    </div>
    <div class="indicator"></div>
  </div>
</div>
<div class="item2">
  <div class="edit">
    <div class="feature-box">
      <div class="upload-options">
        <label class="label2" for="file-input2">
    <img class="icon" src="https://uploads-ssl.webflow.com/57e5747bd0ac813956df4e96/5aebae14c6d254621d81f826_placeholder.png">
    <img class="prev" src="http://inddc.in/webroot/assets/img/sample/shortcode/logo/1.png">
        <input id="file-input2" type="file" name="image" class="image2" accept="image/*"/>
      </label>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

0 个答案:

没有答案