我想在我的yii2应用程序中实现这样的想法: How to preview multiple images before upload? 我需要显示多个图像(最多5个) 我的代码有什么问题?当我选择文件时没有任何事情发生。
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class="col-lg-6">
<p class="add_photo"><img class="describe_images" src="photo.png"></img>Добавить фото(до 5 штук)</p>
<input id="file-input" type="file" multiple>
<script>
function previewImages() {
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
}, false);
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages, false);
</script>
</div>
<div class="col-lg-6 pixels-line">
<div class="preview"></div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
答案 0 :(得分:0)
而不是.addEventListener("change", previewImages, false);
尝试.addEventListener("click", previewImages, false);
。由于单击UI按钮不执行任何操作,因此元素必须具有DOM更改才能使事件侦听器当前执行。