0

为了上传图像并阻止它占用太多空间,我编写了这段代码。不幸的是,它会导致图像失真。是否可以获取输入图像的宽度和高度,然后将其除以 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);
4

1 回答 1

0

您可以在此处使用一个小类,并在设置widthautomax-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>标签内的所有图像中,包括当前和未来的元素。

于 2020-03-27T06:37:26.497 回答