繁体   English   中英

使用html输出标签时,有没有一种方法可以控制图像的大小?

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

我正在使用以下代码上传图像以供查看,然后再传递给服务器。 我想使用css对图像的大小施加限制。 CSS对图像不起作用,因为它是通过输出呈现的。 有没有解决的办法? 我尝试将CS​​S属性添加到其周围的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 ,但是background属性必须使用url设置为css的图像。

您也可以像这样简单地覆盖cssimg标签:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM