所以我正在为客户开发网站。我需要帮助的相关区域是照片的上传和预览区域。照片不需要在这个过程中传输,这只是上传和预览与示例的比较—— dentry 诊所。
有 5 张示例照片和 5 个上传部分,他们可以在示例旁边预览照片。
我使用的代码是:
<style>
/* Image Designing Propoerties */
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<script type="text/javascript">
/* The uploader form */
$(function () {
$(":file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
$('#yourImage').attr('src', e.target.result);
};
</script>
<input type='file' />
</br><img id="myImg" src="#" alt="your image" height=247 width=330>
所以这是关键。当我将此代码用于一个代码块(构建在 Squarespace 平台上)时,它会上传并显示该 block 的照片,没问题。
当我将它添加到其他区域时,上传目标要么更改为不同的区域,要么调整它,我有两个 block 来显示相同的图像,但我不确定如何编写它以便每个 block 显示它的自己的形象,我不确定我忽略了 ID 或 SRC 明智的是什么会触发它。
如果需要,我很乐意发送链接和站点密码以供进一步检查。在此先感谢,第一次使用 stackoverflow 帮助聊天。
最佳答案
我刚刚创建了一个 function readurl(a)
,我将参数 a
传递给它。此参数将告诉函数有关 input
的 id
和 img
的 id
我们要预览图像的地方.因为 html
中所有 elements
的 id 应该是不同的。
HTML 和 JS 代码
function readurl(a)
{
input=document.getElementById('input'+a);
if (input.files && input.files[0])
{
var reader = new FileReader();
reader.onload = function (e)
{
document.getElementById('blah'+a).src=e.target.result;
};
reader.readAsDataURL(input.files[0]);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="new_img_container" >
<label id="file">Upload image
<input onchange="readurl(1)" id="input1" name="product_img" type="file" name="image" size="60" required>
</label>
<br>
<img id="blah1" src="../images/product_image.png" alt="product_image" >
</div>
<br><br>
<div class="new_img_container" >
<label id="file">Upload image
<input onchange="readurl(2)" id="input2" name="product_img" type="file" name="image" size="60" required>
</label>
<br>
<img id="blah2" src="../images/product_image.png" alt="product_image" >
</div>
</body>
</html>
我没有为样式添加任何 CSS。
关于javascript - 图像上传和预览选项,代码不允许显示不同的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54965766/