【问题标题】:Is there a way to control the size of an image when using html output tag?使用 html 输出标签时,有没有办法控制图像的大小?
【发布时间】:2015-05-16 16:33:50
【问题描述】:

我正在使用以下代码上传图像以供查看,然后再将其传递到我的服务器。我想使用 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);

【问题讨论】:

  • .list 目标和元素具有 class list,而您的具有 id
  • 这是真的,但它没有效果。我在试验,忘记改回来了。对此感到抱歉,现在正在编辑。
  • 那么你需要为 img 元素设置 max-width 和 -height ,而不是容器元素……

标签: javascript html css html-input


【解决方案1】:

最简单的方法是使用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 属性必须设置为css 中图像的url。

您也可以像这样简单地覆盖css 中的img 标签:

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

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

【讨论】:

  • “最简单的方法是使用高度和宽度 img 标签属性”——这可能会扭曲图像——至少你必须阅读实际的图像尺寸,然后相应地计算新的宽度/高度,使其仍以其原始纵横比显示。
  • 谢谢先生!这个小小的见解对我来说很重要。顺便说一句,如果我想分配一个 src,有没有一种简单的方法可以做到这一点?另外,我想你的答案是在 px 中,有没有办法在 em 中做到这一点?我的意思是有办法在 css 中对此进行规范吗?
  • 嗯,有很多可能的方法,但如果你提出另一个问题,我很乐意回答:)
  • @Urahara,覆盖图像标签是什么意思?我的意思是,css中没有img标签。
猜你喜欢
  • 1970-01-01
  • 2021-10-19
  • 2011-04-26
  • 2015-05-14
  • 2021-01-30
  • 2012-10-19
  • 2013-10-22
  • 2010-10-27
  • 1970-01-01
相关资源
最近更新 更多