宽度和高度未定义- Javascript/jQuery
Width and height undefined - Javascript/jQuery
我有一个宽度和高度的问题。
我的函数:
function testImageSize(testSrc) {
var imageTestLink = "";
var link = testSrc.attr("src");
link = link.replace("/thumbs/", "/images/");
imageTestLink = link.replace(".thumb", "");
var theImage = new Image();
theImage.src = imageTestLink;
console.log(imageTestLink);
var rw = theImage.width;
var rh = theImage.height;
console.log(rw, rh);
}
我的问题是,当我运行这个函数imagesTestLink
返回始终正确的链接到图像。但rw
和rh
有时会在控制台返回0 0
值。有人能帮我解决这个问题吗?我读了很多题目,但我没有找到我的答案。
问候,Fantazy
问题是在函数结束之前图像可能不会被加载。你需要使用回调来处理…
var rw;
var rh;
function testImageSize(testSrc, callback) {
var imageTestLink = "";
var link = testSrc.attr("src");
link = link.replace("/thumbs/", "/images/");
imageTestLink = link.replace(".thumb", "");
var theImage = new Image();
// create an event handler that runs when the image has loaded
$(theImage).on("load", function() {
rw = theImage.width;
rh = theImage.height;
callback();
});
console.log(imageTestLink);
theImage.src = imageTestLink;
}
testImageSize("/thumbs/thumbnail.jpg", function() {
// this function will only be executed once the image has loaded
console.log(rw, rh);
});
基本上,你创建了一个函数,你想在图片加载时运行,你已经得到了大小,你把它传递给testImageSize
。它会加载图片一旦完成它会获取图片的大小然后调用你传入的函数
相关文章:
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- Javascript(jQuery)给了我奇怪的结果
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- Javascript/jQuery中的并行Ajax调用
- 我可以在Javascript/jQuery中使用一个变量作为键吗
- Javascript/Jquery/PHP加载页面-如何
- Javascript/Jquery Blob not showing Chrome PDF
- 如何使用javascript/jquery获取iframe的URL的锚点属性
- OnClick/Onhover Javascript/jquery
- 如何从javascript/jquery中的复选框中获取布尔值
- javascript/jquery将utc转换为短格式的本地时间
- 在不设置协议的情况下,使用javascript/jquery更改iframe-src
- 如何向这个javascript/jquery函数添加参数
- 用JavaScript/jQuery点击图片,选中多个方框
- 使用Javascript/JQuery获取JSON GET数据
- 从数组中删除元素的最佳方法是:javascript/jquery
- Javascript/jQuery压缩一个图像正确的评论帖子,并使用Ajax Laravel 5.2保存到控制器中
- 用DRY方式Javascript/JQuery动态替换HTML
- 类似Javascript JQuery的库
- 如何在 Javascript/jQuery 中获取一些随机下拉列表的选定值