在尝试实施之前使用JSFiddle:http://jsfiddle.net/qa9m7t33/
尝试实施后:http://jsfiddle.net/z1k538sm/
我找到了如何调整图片的大小,但我相信这不是上传之前的一个例子,我对此很新。我认为错误的是变量;'
var width = e.target.result.width(); // Current image width
var height = e.target.result.height(); // Current image height
我也遇到了将文字集中在上传字段中的问题。
答案 0 :(得分:1)
不完全是Js对此的回答,而是为元素添加行高CSS
#file {
line-height: 37px;
}
将完成工作,我想如果你想让它成为jQuery你可以做到
$('#file').css('line-height',$('#file').height() + 'px');
关于问题的第一部分,我无法提出问题,抱歉。
编辑: 第一部分试试这个:
var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'});
var fileInput = $(':file').wrap(wrapper);
fileInput.change(function(){
readURL(this);
})
$('#file').click(function(){
fileInput.click();
}).show();
function readURL(input) {
$('#blah').hide();
if (input.files && input.files[0]) {
var goUpload = true;
var uploadFile = input.files[0];
if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(uploadFile.name)) {
$('#file').effect( "shake" );
$('#file').text('You must select an image file only');
setTimeout(function() { $('#file').text('Choose file');},5000);
goUpload = false;
}
if (uploadFile.size > 2000000) { // 2mb
//common.notifyError('Please upload a smaller image, max size is 2 MB');
$('#file').text('Please upload a smaller image, max size is 2 MB');
setTimeout(function() { $('#file').text('Choose file');},5000);
goUpload = false;
}
if (goUpload) {
$('#file').text("Uploading "+uploadFile.name);
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image;
img.onload = function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = this.width; // Current image width
var height = this.height; // Current image height
// Check if the current width is larger than the max
if (width > maxWidth) {
ratio = maxWidth / width; // get ratio for scaling image
$('#blah').css("width", maxWidth); // Set new width
$('#blah').css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
}
// Check if current height is larger than max
if (height > maxHeight) {
ratio = maxHeight / height; // get ratio for scaling image
$('#blah').css("height", maxHeight); // Set new height
$('#blah').css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
$('#blah').attr('src', this.src).show();
$('#file').text(uploadFile.name);
};
img.src = reader.result;
}
reader.readAsDataURL(uploadFile);
}
}
}
你不应该有它所说的部分:
47 var width = uploadFile.width(); // Current image width
48 var height = uploadFile.height(); // Current image height
两次,因为你只是将你的工作从之前的IF中删除。
同样,FileReader()似乎无法获取图像大小属性,因此具有FileReader,创建图像Object,然后使图像Object的onload完成所有工作。