我有以下代码,它使用HTML的output属性返回一个图像。我想要能够缩放/编辑这个图像的最大宽度和最大高度。我还想给这个图像分配一个SRC。
我的HTML:
<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);发布于 2015-03-14 04:34:31
因此,如果您真的想使用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操作:setcolor
发布于 2015-03-14 04:56:03
为什么不只是在您的css中有.thumb{max-height:35px;max-width:75px;},当您创建新元素时,设置class属性,并且css将应用于该元素。另外,为什么要创建一个span,然后将innerHTML设置为图像?为什么不直接创建图像呢?
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);我希望这能帮到你。编码愉快!
https://stackoverflow.com/questions/29045438
复制相似问题