简体   繁体   中英

Extract image from input

I have jsfiddle

If you will look in console.log you will see the img will appear inside of input but I want to append the image right after div.pic-box what can I do?

Here is a part of code..jS :

$(function() {
  $("input[type=file]").on("change", function(e) {
    var output = $("<img/>", {
      src: URL.createObjectURL(e.target.files[0])
    });
    $(e.target).append("div.pic-box").html(output)
  });
});

尝试将元素附加到目标的父级:

$(e.target.parentNode).append("div.pic-box").html(output)

Replace

$(e.target).append("div.pic-box").html(output); 

to

output.appendTo("div.pic-box");

That may match your expection.

Try this:

$(function() {
  $("input[type=file]").on("change", function(e) {
    var output = $("<img/>", {
      src: URL.createObjectURL(e.target.files[0])
    });
    console.log(e.target);
    $(this).closest("div.pic-box").parent().children("img").remove();
    $(this).closest("div.pic-box").after(output);
    
  });
});

Fiddle

You can check the parent div and add your img after.

$(this).closest("div").after(output)

Please try below:

 $("input[type=file]").on("change", function(e) { var output = $("<img/>", { src: URL.createObjectURL(e.target.files[0]) }); console.log(e.target); $(this).closest("div").after(output) });
 .fileContainer { overflow: hidden; position: relative; } .fileContainer [type=file] { cursor: inherit; display: block; font-size: 999px; filter: alpha(opacity=0); min-height: 100%; min-width: 100%; opacity: 0; position: absolute; right: 0; text-align: right; top: 0; } .pic-box { background-color: blue; height: 100px; margin-left: 3%; margin-top: 3%; } .plus-box { color: red; font-size: 60px; text-align: center; top: 30px; } .padding-box { padding-left: 5px !important; padding-right: 5px !important; padding-top: 10px !important; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="tabs-2" class="tab-content"> <div class="tab-elements"> <div class="row"> <div class="col-xs-4 fileContainer padding-box"> <div class="pic-box"> <div class="plus-box">xyz</div> <input type="file" accept="image/*"> </div> </div> <div class="col-xs-4 fileContainer padding-box"> <div class="pic-box"> <div class="plus-box">xyz</div> <input type="file" accept="image/*"> </div> </div> <div class="col-xs-4 fileContainer padding-box"> <div class="pic-box"> <div class="plus-box">xyz</div> <input type="file" accept="image/*"> </div> </div> <div class="col-xs-4 fileContainer padding-box"> <div class="pic-box"> <div class="plus-box">xyz</div> <input type="file" accept="image/*"> </div> </div> </div> </div> </div>

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