有没有办法在使用 html 输出标签时控制图像的大小

Is there a way to control the size of an image when using html output tag?

本文关键字:控制 图像 标签 输出 html 有没有      更新时间:2023-09-26

我使用以下代码上传图像以供查看,然后再将其传递到我的服务器。 我想使用 css 对图像的大小进行约束。 CSS 对图像没有影响,因为它是通过输出呈现的。有没有办法解决这个问题?我尝试将 CSS 属性添加到其周围的div 中,但这也不起作用。

该 HTML:

  <input type="file" id="files" name="files[]" file-model="myFile"/>
  <output id="list" class="resize-image" alt="Image"></output>

CSS:

#list{
  max-width: 15px;
  max-height: 7px;
}

Javascript:

var handleFileSelect = function (evt) {//already set up for multiple files; not what i want to do.
            var files = evt.target.files; // FileList object
            // Loop through the FileList and render image files as thumbnails.
            for (var i = 0, f; f = files[i]; i++) {
                // Only process image files.
                if (!f.type.match('image.*')) {
                    continue;
                }
                var reader = new FileReader();
                // Closure to capture the file information.
                reader.onload = (function(theFile) {
                    return function(e) {
                        // Render thumbnail.
                        var span = document.createElement('span');
                        span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
                        document.getElementById('list').insertBefore(span, null);
                    };
                })(f);
                // Read in the image file as a data URL.
                reader.readAsDataURL(f);
            }
        }
        document.getElementById('files').addEventListener('change', handleFileSelect, false);

简单的方法是使用heightwidth img标签属性。

var span = document.createElement('span');
        span.innerHTML = ['<img height="7" width="15" class="thumb" src="', e.target.result,
        '" title="', escape(theFile.name), '"/>'].join('');
        document.getElementById('list').insertBefore(span, null);

如果您确实想使用此任务.css可以使用background-size,但是必须使用css中的图像的 url 设置background属性。

您也可以简单地覆盖css中的img标签,如下所示:

img{
  max-width: 100px;
  max-height: 100px;
}

在这里你可以测试这两种方法: http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_background-size