我想要的是-(仅用于图像的所见即所得编辑器)当用户单击我的html页面的任何图像时,应该出现“选择文件”按钮选项,而无需编写任何标签,我不想将该图像上传到服务器,因此无需使用 php 或任何其他只是想预览它。 为了实现这个目标我做了什么
//image that already there in html page
<div id="headshot" class="quickFade">
<img id="blah" src="#" alt="your image" />
</div>
//grab the id of parent element of clicked image
$('img').click(function(event){
if (event.target.nodeName == 'IMG'){
var pratik = event.target.parentNode.id;
// creates <input type="file" id="imgInp">
var newElem = document.createElement('input');
newElem.type = "file";
newElem.id = "imgInp";
document.getElementById(pratik).appendChild(newElem);
}
})
// preview the image after uploading the image and then remove the "choose file" button
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$('#imgInp').change(function() {
document.getElementById("imgInp").remove();
readURL(this);
});
这整个代码动态生成<input type="file" id="imgInp">
下面<img id="blah" src="#" alt="your image" />
所以这会像这样
<div id="headshot" class="quickFade">
<img id="blah" src="#" alt="your image" />
<input type="file" id="imgInp">
</div>
上传过程正常,但预览并在预览功能不起作用后删除按钮
但是当我手动输入此代码 <input type="file" id="imgInp">
通过编辑 html 文件,然后在预览功能运行后删除按钮。
感染功能不依赖于此代码 <input type="file" id="imgInp">
位置我的意思是我可以放在任何我想要的地方,并且仍然可以预览并删除功能正在工作,但是当此代码 <input type="file" id="imgInp">
时代码是通过上面的JavaScript动态出现的,那么就会出现这个问题
最佳答案
let $img = null;
const $fileInput = $('<input>', {
appendTo: 'body',
accept: 'image/*',
type: 'file',
hidden: true,
on: {
change: function(ev) {
const F = ev.target.files;
if (!F || !F[0]) return;
if (!(/^image\/(jpe?g|png|gif)$/).test(F[0].type)) return alert('Use images only');
$img.one('load', ev => URL.revokeObjectURL(ev.target.src)).prop('src', URL.createObjectURL(F[0]))
}
}
});
$('img').on('click', function() {
$img = $(this);
$fileInput.click();
});
<div>
<img src="//placehold.it/100x100/0bf"> Click to replace
</div>
<div>
<img src="//placehold.it/100x50/f0b"> Click to replace
</div>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
关于javascript - 通过预览上传来动态更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58019681/