作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想从中随机挑选一张图片:
为了正确显示它,我需要知道这张图片的大小。
我使用 YQL 将这个 json 的结果放在一个变量中(称为 source)。
我将 https 替换为 http 并删除每个反斜杠。
var it = $.parseJSON(source);
var total = it.count-1;
var random = Math.floor((Math.random()*total)+0);
var gagurl = it.items[random];
var gagurldecode = gagurl.replace('\\','');
gagurldecode = gagurldecode.replace('https','http'); //here is the url of the image
但我无法检索此图像的大小。
var img = new Image();
img.src = gagurldecode;
警报(img.height);什么都不返回。
如果我替换
img.src = gagurldecode;
与
img.src = 'http://d24w6bsrhbeh9d.cloudfront.net/photo/1777377_460s.jpg';
有效。
我做错了什么?PS:对不起我的英语!
最佳答案
这一行是不必要的,因为解析 JSON 时斜杠被转义了:
var gagurldecode = gagurl.replace('\\','');
对于您的实际问题,height
和 width
直到图像下载并检查后才会填充。如果浏览器没有看到图像(在 onload
事件处理程序中),这是异步完成的,但如果像硬编码示例中那样从缓存中检索,则可以同步完成:
img.onload = function() {
alert(img.height);
}
这每次都有效。
关于javascript - 9gag 解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063553/
我是一名优秀的程序员,十分优秀!