为了上传图片,同时防止它占用太多空间,我写了这段代码。不幸的是,这将导致图像失真。是否可以取输入图像的宽度和高度,然后将其除以10,以便缩小图像,同时防止其变形。然后“发布”它。
HTML:
<button id="publish-button" onclick="publish();">Publish</button>
<p>Images</p>
<input id="image-file" type="file"/>
<ul id="posts"></ul>Javascript:
var image = document.getElementById("posts");
var image = document.createElement("img");
var imageInput = document.getElementById('image-file');
image.src = URL.createObjectURL(imageInput.files[0]);
image.style.height = 100;
image.style.width = 100;
para.appendChild(image);发布于 2020-03-27 14:37:26
您可以在这里使用一个小类,并在类中将width设置为auto,将max-height设置为100px,以便缩小图像并保持纵横比不变。
function publish(e) {
var image = document.getElementById('img');
image.src = URL.createObjectURL(e.target.files[0]);
image.className = "img";
image.onload = function() {
URL.revokeObjectURL(image.src)
}
};.img {
width: auto;
height: 100%;
max-height: 100px;
}<input id="image-file" type="file" accept="image/*" onchange="publish(event)" /><br/>
<img id="img" />
此外,如果您将动态图像放在<p>标记内,那么您甚至不需要在js代码中添加类,您只需修改css,如下所示:
p img {
width: auto;
height: 100%;
max-height: 100px;
}它会将css添加到<p>标记内的所有图像中,包括当前和将来的元素。
https://stackoverflow.com/questions/60880861
复制相似问题