是否可以仅通过jQuery将图像替换为用户动态选择的另一个图像

Is it possible to replace an image with another one selected by the user on the fly via jQuery alone?

本文关键字:图像 替换 用户 选择 另一个 动态 jQuery 是否      更新时间:2023-09-26

我让用户选择一个图像,我想更改动态显示的图像,而不必依赖 PHP 等服务器端脚本?

基本上,我有一个如下所示的 HTML:

<input type="file" id="file" name="file" />
<img id="imagedisplay" src="http://path/to/some/image.jpg" />

然后在jQuery方面,我有以下内容:

$('#file').change(function(e){
    alert($(this).val());
});

我希望将imagedisplaysrc替换为用户选择的本地引用到其系统的,但$(this).val()只显示文件名,所以我无法将其引用为源。

您可以使用 FileReader API。

FileReader 对象允许 Web 应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区(的内容。

它的方法FileReader.readAsDataURL((

readAsDataURL 方法用于读取指定 Blob 或文件的内容。

注意:它适用于现代浏览器

$(document).ready(function() {
  $('#file').change(function(e) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#imagedisplay').attr('src', e.target.result);
    }
    reader.readAsDataURL(this.files[0]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
<img id="imagedisplay" src="" />