dongpanbo4727 2017-02-15 13:34
浏览 105

使用javascript在yii2中预览图像

I want to implement in my yii2 app somethink like that: How to preview multiple images before upload? I need to show multiple images(max 5) Whats wrong with my code? When I choosed file nothing happened.

<?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(); ?>
  • 写回答

1条回答 默认 最新

  • dragam0217 2017-02-15 14:41
    关注

    Instead of .addEventListener("change", previewImages, false); try .addEventListener("click", previewImages, false);. As clicking on the UI button does nothing, the element would have to have a DOM change for the event listener to execute currently.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘