1

我有一个输入字段,我通过浏览按钮在其中插入值现在我想将该值从输入字段复制到 src 标记,以便我可以预览用户刚刚上传的图像

这是我的代码

<input class="text-input" type="text" name="logo" id="logo" onclick="tinyBrowserPopUp('image','logo','client_logos');"/>

我想从上面的输入字段中复制选定的值到

<img src="myimage" /> 
4

3 回答 3

1

您不能直接从用户的计算机上显示它,而是需要先将其上传到您的服务器,然后再显示。使用 ajax 上传文件将创建您想要的相同效果。还可以看看:FileReader API @ MDN

更新:由于您已经在服务器上拥有图像,请尝试以下代码

试试这个代码:

HTML:

<input class="text-input" type="text" name="logo" id="logo" onclick="tinyBrowserPopUp('image','logo','client_logos');" />
<img src="myimage" />

JS:

setInterval(react, 5000);
function react() {
    document.getElementByTagName("img").src = document.getElementByName("logo").value;
}
于 2013-07-05T20:21:30.853 回答
0

在 img 标签中添加一个 id 并使用

var imagepath = $('#logo').val();
$('#myimg').attr('src', imagepath);

在输入更改时触发的函数内部

于 2013-07-05T20:49:04.620 回答
0

我用下面的代码得到了这个。我喜欢将函数放在主体上,这样即使之后通过 AJAX 添加了类,“更改”命令仍然会触发事件。

我的方法确实使用了 jQuery。

HTML:

<input class="text-input" class="classhere" type="text" name="logo" id="logo" />
<div class="imagearea"></div>

JS:

$("body").on("change",".classhere",function(){
  //Equivalent of getElementById
  var fileInput = $(this)[0];//returns a HTML DOM object by putting the [0] since it's really an associative array.
  var file = fileInput.files[0]; //there is only '1' file since they are not multiple type.

  var reader = new FileReader();
  reader.onload = function(e) {
       // Create a new image.
       var img = new Image();

       img.src = reader.result;
       $(".imagearea").html(img);
   }

   reader.readAsDataURL(file);//attempts to read the file in question.
});

这种方法使用 HTML5 文件系统 API 来读取图像并将其放入新的 javascript img 对象中。这里的关键是 readAsDataURL。如果您使用 chrome 检查器,您会注意到图像以 base64 编码存储。

读者是异步的,这就是它使用回调函数onload的原因。因此,请确保任何需要图像的重要代码都在 onLoad 中,否则您可能会得到意想不到的结果。

于 2013-12-12T04:16:19.257 回答