img标记的宽度错误
wrong width of img tag
我试图为我的应用程序构建一个图像上传器。所以我需要调整图像的大小。但我经常在img标记中得到错误的宽度值。不是每次都这样。但有时当我加载图片3次时,或者有时如果我更改图片,就会有旧的宽度。但也不是每次都有。
$(document).on('pageshow', '#profil', function () {
$('#content').height(getRealContentHeight());
var max_height = getRealContentHeight();
var max_width = $(window).width();
var username = getUrlParameter('user');
var data;
var x, y, w, h;
var preview;
var reader;
var pic = document.getElementById('pic');
var jcrop_api;
$('#upload').bind("change", function () {
preview = new Image();
var file = document.querySelector('input[type=file]').files[0];
reader = new FileReader();
reader.onloadend = function () {
if (jcrop_api) {
jcrop_api.setImage(reader.result);
}
preview.src = reader.result;
document.getElementById('pic').src = preview.src;
alert(pic.height); //there is the false value...sometimes....
alert(pic.width);
var size = calculateAspectRatioFit(pic.width, pic.height, max_width, max_height);
alert("heigth:" + size.height);
alert("width:" + size.width);
// document.getElementById('pic').height = size.height;
// document.getElementById('pic').width = size.width;
jQuery(function ($) {
$('#pic').Jcrop({
aspectRatio: 1,
minSize: [50, 50],
maxSize: [300, 300],
onChange: showCoords,
onSelect: showCoords
}, function () {
jcrop_api = this;
});
});
function showCoords(c) {
x = c.x;
y = c.y;
w = c.w;
h = c.h;
};
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return {width: srcWidth * ratio, height: srcHeight * ratio};
}
};
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
});
$('#continue').bind("click", function () {
//ajax upload
});
});
可能是两个问题之一:
1( 你是在css或inline中设置"#pic"元素的高度或宽度尺寸吗?您可能得到的是元素的尺寸,而不是图像的尺寸。
2( 您正在对此img设置"src",但不等待图像加载。你可以试试:
$("#pic").on("load", function() {
//get dimensions now
});
你必须显示图像吗?否则,您可以使用:将其加载到js中
var img = new Image();
然后使用jQuery加载事件处理程序,如上所述。然后设置:
img.src = 'image url';
您可以尝试以下操作吗:
$("#pic").height();
$("#pic").width();
$("#pic").outerHeight();
$("#pic").outerWidth();
代替:
pic.height
pic.width
看到合适的了吗?
相关文章:
- Node.js v6.2.0类扩展不是函数错误
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- 如何更改<svg>标记为<img>用js标记
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 如何捕获 iframe 内的 img 标记返回的 404(未找到)错误
- JavaScript img onclick 引用错误才能正常工作
- 错误验证 W3C HTML5 img noscript facebook.com.
- 我收到错误.我需要创建 img 标签
- 如何使用 PhantomJS 进行单元测试时防止 img src 404 错误
- 在该应用程序上运行SortSite时,此IMG链接到图像的MIME类型错误的文件
- 捕获<的img加载错误;img>页面加载后创建的标签(例如通过AJAX)
- 在呈现img html组件时重定向或显示错误消息
- 更改Img属性时出现填充数组错误
- 错误nan插入带有循环的img
- Http:403禁止错误时,试图加载img SRC与谷歌个人资料的图片
- 浏览器视窗宽度单位错误与img标签
- 使用handlebars.js时无法检测IMG jquery错误事件.我怎样才能修复这些破碎的图像
- img标记的宽度错误
- 未捕获的类型错误:不能设置属性'onclick'如果为null,则输入type="img&qu