使用 HTML 输出标记查看可缩放图像并分配 src

Working with HTML output tag to view scalable image and assign src

本文关键字:图像 缩放 分配 src 输出 HTML 使用      更新时间:2023-09-26

我有以下代码,它使用 HTML 的输出属性返回图像。 我希望能够以最大宽度和最大高度缩放/编辑此图像。我还想为此映像分配一个 SRC。

我的网页:

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

我的JS:

  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 height="35" width="75" 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);

所以如果你真的想在这种情况下使用css属性,你必须使用style属性内联注入它们

 var span = document.createElement('span');
        span.innerHTML = ['<img height="35" width="75" class="thumb" src="',
        e.target.result,
        'style="max-height:25px; max-width:25px;"', // You can manipulate that dynamically using 
        '" title="',
        escape(theFile.name),
        '"/>'].join('');
        document.getElementById('list').insertBefore(span, null);
    };

检查这个动态 css 操作:http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_css_setcolor

为什么不在你的css中.thumb{max-height:35px;max-width:75px;},当你创建新元素时,设置class属性,css将应用于该元素。另外,为什么要创建一个范围,然后将内部HTML设置为图像?为什么不直接创建映像?

.CSS

.thumb{max-height:35px;max-width:75px;}

创建镜像

var Img = document.createElement('img');
// .setAttribute(AttributeType, Attribute Value);
Img.setAttribute('class','thumb'); //Class Attribute
Img.setAttribute('src',e.target.result);//Src Attribute
document.getElementById('list').insertBefore(Img, null);

我希望这有所帮助。祝您编码愉快!