我想在单击“附加文件”按钮(filebtn css 类)时获取图像,并在 div 中显示该图像(upload-img CSS 类)。
这是我的代码:
<script>
$('.file').change(function () {
$(this).next('.file_selected').val($(this).val()) });
$('.upload-img').hide();
$('.fileinput').click(function(){
$(this).parent().find('.upload-img').slideDown();
});
</script>
<div class="fileinput form-control">
<input type="file" id="" name="" class="file" />
<input type="text" class="file_selected" value="Upload Related Photo" />
<input type="button" class="filebtn" value="Attach File" />
</div>
<div class="upload-img">
<img src="images/profile.jpg" alt="profile" />
</div>
<br />
<style>
.fileinput { position:relative; cursor:pointer; overflow:hidden; z-index:1; padding:0; display:inline-block;}
.fileinput input[type=file] { position:absolute; width:100%; height:100%; filter: alpha(opacity=0); opacity: 0; left:0; top:0; cursor:pointer; z-index:9; }
.fileinput input[type=text] { background:none; border:none; }
.filebtn { background:#aaaaaa; color:#fff; position:absolute; right:0; height:100%; top:0; padding:0 12px; cursor:pointer; border:0; text-transform:uppercase; font-size:14px;}
.file_selected{height:37px; padding:6px 12px; width:78%;}
</style>
最佳答案
您可以在 upload-img div 中添加 canvas 元素。 我用的是 jQuery。这里的例子:
html代码:
<input id="fileUploader" type="file" name="Files" onchange="fileUpload()" />
<div class="upload-img">
<canvas class="image-preview" id="imageCanvas"></canvas>
</div>
CSS:
.image-preview {
margin-top: 10px;
height: 100px;
}
js代码:
var canvas = $("#imageCanvas")[0];
var fileInput = $("#fileUploader")[0];
var imgHeight = 200;
function fileUpload () {
var ctx = canvas.getContext('2d');
var reader = new FileReader();
reader.onload = function (event) {
var img = new Image();
img.onload = function () {
var height, width;
if (imgHeight) {
height = imgHeight;
var zoom = imgHeight / img.height;
width = img.width * zoom;
} else {
height = img.height;
width = img.width;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
}
img.src = event.target.result;
}
reader.readAsDataURL(fileInput.files[0]);
}
关于javascript - 我想使用 jQuery 获取并显示 div 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31744623/